Reputation: 1029
I'm trying to read a json structure into a global variable, but cannot seem to get it to work. I am using a callback for processing once it's read from the file (that part is working).
I'd like to have "source_files" populated.
var fs = require('fs');
var source_files = [];
function readConfig(callback) {
fs.readFile('data.json', 'utf-8', function (err, content) {
if (err) return callback(err);
callback(content);
});
}
readConfig(function(config) {
var settings = JSON.parse(config);
var inputs = settings.inputs;
for (var id=0; id < inputs.length; id++) {
source_files.push(inputs[id].replace('./',''));
}
});
console.log(source_files);
Upvotes: 1
Views: 3434
Reputation: 38777
As already stated, readFile
is asynchronous. If this is just start-up initialising code (i.e. doesn't matter if it blocks) you could use readFileSync
instead (which throws err
or returns content
).
However, if readConfig
can also be called in response to later input (e.g. a POSIX signal or a TCP request) then you must keep it asynchronous or risk blocking other I/O.
Upvotes: 2
Reputation: 1074208
Remember that readFile
is asynchronous. Your last line, console.log(source_files)
, will run before the readFile
callback has been called, and thus before the readConfig
callback is called. You need to move that into the readConfig
callback.
With your code as-is, here's what happens:
readConfig
.readConfig
calls readFile
.readFile
starts the asynchronous read operation and returns.readConfig
returns.source_files
, which is empty.readFile
operation finishes and the callback is called. It calls the readConfig
callback.readConfig
callback populates source_files
, but it's a bit like a tree falling in the forest at that point, as nothing observes that. :-)Upvotes: 5