0

The line of code below provides and output through the console but I want to assign the console.log data to a variable Below is a sample code

  const SerialPort = require('serialport')
const Readline = require('@serialport/parser-readline')
const port = new SerialPort('COM1', { baudRate: 9600 })

const parser = new Readline()
port.pipe(parser)



parser.on('data', line => variableName = `> ${line}`);

console.log(variableName);
10
  • 1
    Does line => variableName = `> ${line}` not work? Commented Jun 11, 2020 at 23:38
  • 2
    Doing this requires understanding of variable scope and the asynchronous nature of callbacks. This guide explains it very nicely. Commented Jun 11, 2020 at 23:40
  • @JohnMontgomery confirmed but does not work ! Commented Jun 11, 2020 at 23:45
  • What do you mean exactly? Are you getting an error? Is something unexpected happening? Commented Jun 11, 2020 at 23:49
  • 2
    Does this answer your question? How do I return the response from an asynchronous call? Commented Jun 12, 2020 at 0:09

1 Answer 1

2

This function

line => variableName = `> ${line}`

isn't getting invoked, because the program hasn't gotten to the next tick of the event loop before you're calling console.log. This will never work. If you want to log that outcome, log it inside the .on callback

line => {
  const variableName = `> ${line}`;
  console.log(variableName);
}

I wrote it like that because the implicit return from the un-bracketed arrow function wasn't returning to anything anyway.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.