用require和fs.readFile读取json文件的内容

假设对于来自API的每个响应,我需要将响应中的值映射到我的Web应用程序中的现有json文件,并显示json中的值。 在这种情况下读取json文件有什么更好的方法? 要求或fs.readfile。 请注意,可能有数千个请求同时进入。

请注意,我不希望在运行时文件有任何更改。

request(options, function(error, response, body) { // compare response identifier value with json file in node // if identifier value exist in the json file // return the corresponding value in json file instead }); 

我想你会JSON.parse JSON文件的比较,在这种情况下, require更好,因为它会立即parsing文件,它是同步的:

 var obj = require('./myjson'); // no need to add the .json extension 

如果你有成千上万个使用这个文件的请求,那么在你的请求处理程序之外需要它,就是这样:

 var myObj = require('./myjson'); request(options, function(error, response, body) { // myObj is accessible here and is a nice JavaScript object var value = myObj.someValue; // compare response identifier value with json file in node // if identifier value exist in the json file // return the corresponding value in json file instead }); 

fs.readFile有两个版本,它们是

asynchronous版本

 require('fs').readFile('path/test.json', 'utf8', function (err, data) { if (err) // error handling var obj = JSON.parse(data); }); 

同步版本

 var json = JSON.parse(require('fs').readFileSync('path/test.json', 'utf8')); 

使用require来parsingjson文件如下

 var json = require('path/test.json'); 

但是,请注意

  • require是同步的并且只读取一次文件,接下来的调用将从caching中返回结果

  • 如果您的文件没有.json扩展名,那么require不会将该文件的内容视为JSON

如果在testing中处理JSON装置,请使用node-fixtures 。

该项目将寻找一个名为夹具的目录,该目录必须是您的testing目录的子目录才能加载所有的灯具(* .js或* .json文件):

 // test/fixtures/users.json { "dearwish": { "name": "David", "gender": "male" }, "innaro": { "name": "Inna", "gender": "female" } } 
 // test/users.test.js var fx = require('node-fixtures'); fx.users.dearwish.name; // => "David"