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

10.3k views Asked by At

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?

3

There are 3 answers

0
Itzik.B On BEST ANSWER

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');
2
C. Mürtz On

If I see it right Readline is a class not function! Try this:

parser: SerialPort.parsers.Readline

Check this out and let me know if it works! https://github.com/EmergingTechnologyAdvisors/node-serialport#serialportparsers--object

0
akmozo On

A working version of your code, you've just to instantiate the Readline class :

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

var myPort = new serialport(portName, {
    baudRate: 9600,
    parser: new 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);
}

and you can run using node index.js COM5, for example, to get something like this :

Open connections!
on Data 123456789

Hope that can help.