SerialPort lib - "parsers.readline is not a function" Error - NodeJS

itzikb picture itzikb · Sep 3, 2017 · Viewed 7.3k times · Source

I have copied this code:

var serialport =require("serialport");
var SerialPort = serialport.SerialPort;
var portName = process.argv[2];

var myPort = new SerialPort(portName,{
    baudRate: 9600,
    parser:serialport.parsers.readline("\r\n")
})

myPort.on('open',onOpen);
myPort.on('data',onData);

function onOpen(){
    console.log("Open connections!");
}

function onData(data){
    console.log("on Data "+data);
}

from this video: https://www.youtube.com/watch?v=rhagmAv35Kk

I would like to stream the data from serial port from my pc into a NJS code. when i run the code i get this error:

c:\njs>node main.js
C:\njs\main.js:7
        parser:serialport.parsers.readline("\r\n")
                                  ^

TypeError: serialport.parsers.readline is not a function
    at Object.<anonymous> (C:\njs\main.js:7:28)
    at Module._compile (module.js:541:32)
    at Object.Module._extensions..js (module.js:550:10)
    at Module.load (module.js:458:32)
    at tryModuleLoad (module.js:417:12)
    at Function.Module._load (module.js:409:3)
    at Module.runMain (module.js:575:10)
    at run (bootstrap_node.js:352:7)
    at startup (bootstrap_node.js:144:9)
    at bootstrap_node.js:467:3

c:\njs>

anyone know why it can't recognize the function?

Answer

itzikb picture itzikb · Sep 3, 2017

The problem was the version of the module. accordding to the lastest version this code should do the work:

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