0

I'm writng a node.js app to read messages from Serial Port. Reading data and logging it into console works fine, althought I'm wondering how to save data value from Serial Port to a variable. I want to pass it further to a MySQL, so I need the data to be stored in variable. I tried to use global variable, but it keeps saying "undefined". I also tried to pass the value using return in js function, but it doesn't work too. Here's my code:

var SerialPort = require('serialport');
const parsers = SerialPort.parsers;
const parser = new parsers.Readline({
    delimiter: '\r\n'
});

var port = new SerialPort('COM10',{ 
    baudRate: 9600,
    dataBits: 8,
    parity: 'none',
    stopBits: 1,
    flowControl: false
});

port.pipe(parser);

parser.on('data', function(data) {
    
    console.log('Received data from port: ' + data);
});

Please tell me how to store data from parser.on in a variable.

1 Answers1

0

Doesn't variable = data;work?

  • It works and assigns a value, but I don't know how to get this value outside **parser.on()** function. I can **console.log** it inside function, but outside value is **undefined**. – machofvmaciek Nov 29 '21 at 20:25
  • I think that is because your variable has function scope. Try defining the variable before the function, like this: ` var variable; parser.on('data', function(data) { variable = data; });` – Andrei Morgovan Dec 02 '21 at 18:09