Search code examples
npmpackageserial-portusbnestjs

Adding serialport and usb in NestJS?


Is it possible to add a serial port and USB package in NestJS? I can't seem to find anything regarding these things.


Solution

    1. In your serial.module.ts, create your custom serial handler service by custom factory providers
    import { SerialHandlerService } from './serial-handler.service';
    @Module({
      providers: [
        {
          provide: 'SerialHandlerService',
          useFactory: SerialHandlerService,
        },
      ],
    })
        export class SerialModule {}
    
    1. Create serial-handler.service.ts in same folder
    import * as SerialPort from 'serialport';
    const Readline = SerialPort.parsers.Readline;
    
    export const SerialHandlerService = () => {
      const port = new SerialPort(
        {YOUR_SERIAL_PORT},
        {
          baudRate: {YOUR_SERIAL_BOADRATE},
          dataBits: {YOUR_SERIAL_DATABITS},
          stopBits: {YOUR_SERIAL_STOPBITS},
          parity: {YOUR_SERIAL_PARITY},
        },
        (err) => {
          if (err) {
            console.error(err)
            // Handle Error
          }
          console.log('success')
        },
      );
      // I'm using Readline parser here. But, You can change parser that you want!
      const parser = new Readline({ delimiter: '\r\n' });
      port.pipe(parser);
    
      port.on('open', () => {
        console.info('port opened');
      });
    
      parser.on('data', (data) => {
        console.log(data);
        // Data is string, process your data below!
      }
    }
    
    1. Add your serial.module.ts in your app.module.ts
    @Module({
      imports: [
        // your other modules...
        SerialModule,
      ],
      controllers: [],
      providers: [],
    })
    export class AppModule {}
    

    [Reference: https://docs.nestjs.com/fundamentals/custom-providers#factory-providers-usefactory]