Search code examples
javascriptnode.jsstreamnode-serialport

Read node-serialport stream line by line


Setup

The official documentation has a part on how to read a node-serialport stream line by line.

I tried the example code:

var SerialPort = require('serialport');
var Readline = SerialPort.parsers.Readline;
var port = new SerialPort('/dev/tty-usbserial1');
var parser = new Readline();
port.pipe(parser);
parser.on('data', console.log);
port.write('ROBOT PLEASE RESPOND\n');

I quickly realised that SerialPort.parsers.Readline should be SerialPort.parsers.readline but even this way I still get an error:

Uncaught TypeError: dest.on is not a function

Problem

Later I realised this functionality is only available since 5.0.0 which is in beta (as of early 2017). I have 4.0.7. So how can I read the stream line by line below version 5?


Solution

  • tl;dr

    Just read it like a regular stream:

    var SerialPort = require('serialport');
    var createInterface = require('readline').createInterface;
    
    var port = new SerialPort('/dev/tty-usbserial1');
    
    var lineReader = createInterface({
      input: port
    });
    
    lineReader.on('line', function (line) {
      console.log(line);
    });
    
    port.write('ROBOT PLEASE RESPOND\n');
    

    Explanation

    Since node-serialport's prototype is Stream, surprisingly you can read it like a regular Stream and the length of this solution is about the same as the one give in the documentation.