0

I'm building a node.js app which will process a lot of numerical data. How do I store in memory data which has been read by fs.readFile, Example:

var somedata = ''; 
fs.readFile('somefile', 'utf8', function(err,data){
 somedata = data; 
});

//fs.readFile is done by now.. 
console.log(somedata) // undefined, why is this not in memory? 

I read file data periodically and currently I have to write what ive read elsewhere and read it again to use it in another function.

How do i just store it in memory? Is this just how javascript works??

gorilla bull
  • 150
  • 9
  • Note: i know readFile returns a promise.. Even if there is a timeout the data read still is not saved to the variable. – gorilla bull Feb 11 '21 at 19:42
  • Duplicate: [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) –  Feb 11 '21 at 19:43
  • 2
    Since you're using node, the short answer is to use readFileSync instead. –  Feb 11 '21 at 19:43
  • @ChrisG yea too bad all the other libraries out there dont have sync versions of their async methods... – gorilla bull Feb 11 '21 at 20:49
  • That's why JS got Promises and `async` and `await`. –  Feb 11 '21 at 23:12

1 Answers1

1

With readFile() the function

function(err,data){
 somedata = data; 
}

gets executed at a later time (asynchronously), which is common JavaScript programming pattern.

JS in a browser and NodeJS is single-thread and uses event-loop for concurrency.

Using readFileSync() will stop execution and return the result of read operation (like you would expect with other languages).

var somedata = ''; 
somedata = fs.readFileSync('somefile', 'utf8');

//fs.readFileSync is done by now.. (which is important difference with readFile()
console.log(somedata) 

References:

Vitalii
  • 2,071
  • 1
  • 4
  • 5