Reputation: 158
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??
Upvotes: -1
Views: 2964
Reputation: 1
In the current version of nodeJs you got a Buffer, something like this <Buffer 66 69 72 73 74 6e 61 6d 65 2c 6c 61 73 74 6e 61 6d 65 2c 61 67 65 2c 66 69 65 6c 64 0a 4a 6f 68 61 6e 6e 2c 4b 65 72 62 72 6f 75 2c 33 30 2c 43 53 0a ... 192 more bytes>
when you try to log data
directly. Instead of that, you can use the toString() method on data
and you will get the actual string read from the file. I suggest you to avoid readFileSync cause on big file it can block the event loop of nodeJS.
Upvotes: -2
Reputation: 2131
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:
Upvotes: 1