将json数据读入Node.js中的全局变量

Kev*_*Old 1 file readfile node.js

我正在尝试将json结构读入全局变量,但似乎无法使其工作.一旦从文件中读取(我正在使用该部分),我正在使用回调进行处理.

我想填充"source_files".

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);
Run Code Online (Sandbox Code Playgroud)

T.J*_*der 5

请记住,这readFile异步的.你的最后一行,console.log(source_files)将运行readFile的回调之前已调用,从而readConfig调用回调函数.你需要移动readConfig回调.

使用您的代码,这是发生的事情:

  1. 它创建了空白数组.
  2. 它叫readConfig.
  3. readConfig电话readFile.
  4. readFile 启动异步读取操作并返回.
  5. readConfig 回报.
  6. 你记录source_files,这是空的.
  7. 稍后,readFile操作结束并调用回调.它调用readConfig回调.
  8. readConfig回调填充source_files,但它是一个有点像树上掉下来在这一点上森林,由于没有观察到.:-)