file - Read json data into global variable in Node.js -
i'm trying read json structure global variable, cannot seem work. using callback processing once it's read file (that part working).
i'd 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; (var id=0; id < inputs.length; id++) { source_files.push(inputs[id].replace('./','')); } }); console.log(source_files);  
remember readfile asynchronous. last line, console.log(source_files), run before readfile callback has been called, , before readconfig callback called. need move into readconfig callback.
with code as-is, here's happens:
- it creates blank array.
 - it calls 
readconfig. -  
readconfigcallsreadfile. -  
readfilestarts asynchronous read operation , returns. -  
readconfigreturns. - you log 
source_files, empty. - later, 
readfileoperation finishes , callback called. callsreadconfigcallback. - the 
readconfigcallback populatessource_files, it's bit tree falling in forest @ point, nothing observes that. :-) 
Comments
Post a Comment