Click here to Skip to main content
15,882,017 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
I'm trying to use fs.readFile() to read the contents of some file and do some operations with the data returned. I'm struggling to store the data into a global variable to use in other functions. In the sample below, how can I "store" the output of the callback function (which I named xxx) in a global variable from the else (the result of the createArray())? To be precise, in this last function createArray() I make later conversions and some operations with the content of the file, but I still don't get it as global but just in the console. Having the value of xxx variable as global would be just enough at the moment. Is it possible to do that with an asyncronous version? Or Am i proceeding in a wrong path ?

function readF(filename){

fs.readFile(filename,{encoding:'utf8', flag:'r'},callback);

}

function callback (err, data) {
if(err)
console.log(err);
else
xxx = createArray(data);
console.log(xxx) // IT IS PRINTED CORRECTLY INSIDE THE FUNCTION
return xxx;
}

console.log(xxx) //PRINTS UNDEFINED

What I have tried:

Tried to store callback function return into a variable, still getting undefined.
Tried with recursion, also didn't work.
Posted
Updated 21-Jun-22 6:02am
v2

Variable xxx only exists inside the callback function. See JavaScript Scope[^]
 
Share this answer
 
fs.readFile is an asynchronous operation. That means it returns before the file has been read.

The file data won't be available until the operation has completed and the callback function has been called.

If you're using a recent version of Node, you can use the Promise-returning API fsPromises.readFile instead:
File system | Node.js v18.4.0 Documentation[^]

That will let you execute the rest of your code when the operation has completed.

You could even use it with async and await to simplify the code:
Modern Asynchronous JavaScript with Async and Await[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900