Reputation: 21
function readTextFile(filename, callback){
var fs = require('fs');
fs.readFile(filename, 'utf8', function(err, data){
if(err){
throw err;
}else{
callback(data);
}
});
}
var set1 = [];
var set2 = [];
var set3 = [];
var set4 = [];
var set5 = [];
readTextFile("./data/names.json", function(text){
var names = JSON.parse(text);
set1 = names.prop1.prop2;
set2 = names.prop1.prop3;
set3 = names.prop1.prop4;
set4 = names.prop5.prop2;
set5 = names.prop5.prop3;
});
console.log(set1);
Running this section of code, using "node jsonRead.js" returns [ ] for any array called in console.log(). This section of code used to work about 80% of the time, but now it doesn't work at all, and I'm not sure why. I would appreciate any advice on how to get it working again.
Upvotes: 1
Views: 963
Reputation: 13005
Node.js paradigm of executing code is Asynchronous , means it will execute next line of code after calling async method . In your above example readTextFile is called and execution will continue to next line . It will not wait for return .
Upvotes: 1
Reputation: 5815
maybe the read process is still going on.
try the console.log(set1);
in the callback:
readTextFile("./data/names.json", function(text){
var names = JSON.parse(text);
set1 = names.prop1.prop2;
set2 = names.prop1.prop3;
set3 = names.prop1.prop4;
set4 = names.prop5.prop2;
set5 = names.prop5.prop3;
console.log(set1);
});
This is cause the callbackfunction of readTextFile
is executed when reading finished, whereas the other code is executed as written.
You could solve this by using Promises. Checkout the q
library for example: https://github.com/kriskowal/q
Upvotes: 1