在Node.js中将json数据读入全局variables
我想读一个JSON结构到一个全局variables,但似乎无法得到它的工作。 我从文件中读取一个callback进行处理(该部分正在工作)。
我想要“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);
请记住, readFile
是asynchronous的 。 最后一行console.log(source_files)
将在调用readFile
callback之前运行,因此在readConfig
callback被调用之前运行。 您需要将其移入 readConfig
callback。
用你的代码,是这样的:
- 它创build空白数组。
- 它调用
readConfig
。 -
readConfig
调用readFile
。 -
readFile
启动asynchronous读操作并返回。 -
readConfig
返回。 - 您logging
source_files
,它是空的。 - 稍后,
readFile
操作结束,并调用callback。 它调用readConfig
callback。 -
readConfig
callback会填充source_files
,但是就像没有任何东西可以观察到的那样,它就像是一棵树在森林中的那一点。 🙂
如前所述, readFile
是asynchronous的。 如果这只是启动初始化代码(即不要紧,如果它阻止),你可以使用readFileSync
来代替(抛出err
或返回content
)。
但是,如果readConfig
也可以被调用以响应稍后的input(例如POSIX信号或TCP请求),那么您必须保持asynchronous或阻止其他I / O。