2

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?

Community
  • 1
  • 1
totymedli
  • 29,531
  • 22
  • 131
  • 165

1 Answers1

2

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.

Community
  • 1
  • 1
totymedli
  • 29,531
  • 22
  • 131
  • 165