Kevin Old
Kevin Old

Reputation: 1029

Read json data into global variable in Node.js

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

Answers (2)

OrangeDog
OrangeDog

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

T.J. Crowder
T.J. Crowder

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:

  1. It creates the blank array.
  2. It calls readConfig.
  3. readConfig calls readFile.
  4. readFile starts the asynchronous read operation and returns.
  5. readConfig returns.
  6. You log source_files, which is empty.
  7. Later, the readFile operation finishes and the callback is called. It calls the readConfig callback.
  8. The 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

Related Questions