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);
Remember that
readFileis asynchronous. Your last line,console.log(source_files), will run before thereadFilecallback has been called, and thus before thereadConfigcallback is called. You need to move that into thereadConfigcallback.With your code as-is, here’s what happens:
readConfig.readConfigcallsreadFile.readFilestarts the asynchronous read operation and returns.readConfigreturns.source_files, which is empty.readFileoperation finishes and the callback is called. It calls thereadConfigcallback.readConfigcallback populatessource_files, but it’s a bit like a tree falling in the forest at that point, as nothing observes that. 🙂