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:

  1. it creates blank array.
  2. it calls readconfig.
  3. readconfig calls readfile.
  4. readfile starts asynchronous read operation , returns.
  5. readconfig returns.
  6. you log source_files, empty.
  7. later, readfile operation finishes , callback called. calls readconfig callback.
  8. the readconfig callback populates source_files, it's bit tree falling in forest @ point, nothing observes that. :-)

Comments

Popular posts from this blog

javascript - backbone.js Collection.add() doesn't `construct` (`initialize`) an object -

c++ - Accessing inactive union member and undefined behavior? -

php - Get uncommon values from two or more arrays -