使用require vs fs.readFile读取json文件内容

vin*_*sty 36 javascript node.js express

假设对于来自API的每个响应,我需要将响应中的值映射到我的Web应用程序中的现有json文件,并显示json中的值.在这种情况下,读取json文件的更好方法是什么?require或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
});
Run Code Online (Sandbox Code Playgroud)

zan*_*ngw 49

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

异步版本

require('fs').readFile('path/test.json', 'utf8', function (err, data) {
    if (err) 
       // error handling

    var obj = JSON.parse(data);
});
Run Code Online (Sandbox Code Playgroud)

同步版本

var json = JSON.parse(require('fs').readFileSync('path/test.json', 'utf8'));
Run Code Online (Sandbox Code Playgroud)

要使用require到如下解析JSON文件

var json = require('path/test.json');
Run Code Online (Sandbox Code Playgroud)

但是,请注意

  • require在调用从缓存返回结果之后,它是同步的,只读取文件一次

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

  • 我想知道为什么我的require('file.json')一直在改变,直到我读到这个 ​​- "require是同步的,只读取文件一次,然后调用从缓存返回结果".这可以通过以下方式绕过:delete require.cache [require.resolve('file.json')] (4认同)

Sha*_*oor 48

我想你会JSON.parse json文件进行比较,在这种情况下,require更好,因为它会立即解析文件并且它是同步的:

var obj = require('./myjson'); // no need to add the .json extension
Run Code Online (Sandbox Code Playgroud)

如果您有使用该文件的数千个请求,请在请求处理程序之外请求一次,就是这样:

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

  • 值得注意的是`require`将缓存文件,因此,如果该json文件的内容在应用程序的整个生命周期中发生变化,您将看不到更新 (3认同)
  • `require` 不是同步的吗?根据 JSON 文件或用例的大小, fs.readFile 应该更好。 (2认同)

Jeh*_*lio 8

因为从来没有人关心写一个基准,而且我觉得需要更快的工作,所以我自己做了一个。

我比较了 fs.readFile(promisified 版本)与 require(无缓存)与 fs.readFileSync。

您可以在此处查看基准测试并在此处查看结果。

对于 1000 次迭代,它看起来像这样:

require: 835.308ms
readFileSync: 666.151ms
readFileAsync: 1178.361ms
Run Code Online (Sandbox Code Playgroud)

那么你应该使用什么?答案并非如此简单。

  1. 当您需要永久缓存对象时使用 require。最好使用 Object.freeze 来避免在应用程序中改变它。
  2. 在单元测试或阻止应用程序启动时使用 readFileSync - 它是最快的。
  3. 当应用程序正在运行并且您不想阻止事件循环时,请使用 readFile 或 promisified 版本。