1

I hope you are well, Is there any way to access the values outside the function? My code is

const SerialPort = require("serialport");
const Readline = require("@serialport/parser-readline");
const port = new SerialPort("COM4");

const parser = port.pipe(new Readline({ delimiter: "\r\n" }));

parser.on("data", function(chunk) {
    valrec = chunk.toString();
    console.log(valrec);
    v = valrec.split(" ");
    var r = v[3];
    var l = v[2];
});

Everything works fine inside the function, but outside it I can't access any of my variables r or l. So please can you help me to reach my variable outside this function to use them in my code.

Or this version of code let me access at least the variable "valrec"

const SerialPort = require('serialport')
const Readline = require('@serialport/parser-readline')
const port = new SerialPort('COM4')

const parser = port.pipe(new Readline({ delimiter: '\r\n' }))

var valrec;
var doStuff = function (param) {
    return console.log(param);
};


parser.on('data', function (chunk) {
    valrec = chunk.toString();
    doStuff(valrec);
});

Thank you very much.

1 Answers1

0

If you define r and l outside the function then you can access them from outside the function. But beware that it will probably not go as you expect. Since the function is asynchronous, it doesn't block the execution of the code, which means that the code after the function will actually run before the function.

const SerialPort = require("serialport");
const Readline = require("@serialport/parser-readline");
const port = new SerialPort("COM4");

const parser = port.pipe(new Readline({ delimiter: "\r\n" }));

// we can define these outside
var r, l;
parser.on("data", function(chunk) {
    valrec = chunk.toString();
    console.log(valrec);
    v = valrec.split(" ");
    // no more "var"s needed here
    r = v[3];
    l = v[2];
});

// THIS WILL NOT WORK
console.log(`r is ${r} and l is ${l}`);

parser.on("end", function() {
    // this will work because we know the data has already been received
    console.log(`r is ${r} and l is ${l}`);
});
Aplet123
  • 33,825
  • 1
  • 29
  • 55
  • thank you, Is this function can help me to get my variable or at least the "valrec"? var valrec; var doStuff = function (param) { // param holds address, when you call it from `$.each()` return param; }; parser.on('data', function (chunk) { valrec = chunk.toString(); doStuff(valrec); //console.log(valrec); //v = valrec.split(" "); //var r = v[3]; //var l = v[2]; }); – Abdullah Fayad Mar 30 '20 at 16:51
  • You can get `valrec` as long as `var valrec;` is located outside the function. – Aplet123 Mar 30 '20 at 16:52