0

I am trying to store the data read by fs in a variable. But I am getting undefined as output.


const fs = require("fs");

var a;
fs.readFile("analogData.txt", "utf8", (err, data) => {
  a = data;
});
console.log(a);

Ravi Shah
  • 5
  • 4
  • Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Robin Zigmond Apr 24 '21 at 11:04

2 Answers2

0
const fs = require("fs");

let a;

fs.readFile("analogData.txt", "utf8", (err, data) => {

a = data;
console.log(a);

});

You might have not created the text file. SO, create it and run the program again.

0

For console.log outside of the callback function, it always gives undefined. Since it executes before "a" variable being set in the callback. Callback function runs after console.log.

Mumin Korcan
  • 101
  • 7