Skip to content
Advertisement

Node.js – Cannot append global variable when using fs

Im trying to read multiple xml files and parse data from them and i managed to do that but now new problem appeared.

allData variable is never changed, no matter what i do. What am i supposed to do here?

I dont know what to do or what to try, this is my first time working with files and im honestly surprised ive managed to come this far.

JavaScript

SOLVED

adjusted code to use.readFileSync()(removed callback function) and now it works.

JavaScript

Advertisement

Answer

The .readdir() and .readFile() methods are async, so in fact the console.log() is executed before all of the readFile operations.

In order to access the allData variable after these operations are complete, you have to either make them sync using .readFileSync() instead or you need to promisify the .readFile() method and wait for all of the promises to resolve.

Advertisement