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.
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)
因为从来没有人关心写一个基准,而且我觉得需要更快的工作,所以我自己做了一个。
我比较了 fs.readFile(promisified 版本)与 require(无缓存)与 fs.readFileSync。
对于 1000 次迭代,它看起来像这样:
require: 835.308ms
readFileSync: 666.151ms
readFileAsync: 1178.361ms
Run Code Online (Sandbox Code Playgroud)
那么你应该使用什么?答案并非如此简单。
| 归档时间: |
|
| 查看次数: |
60337 次 |
| 最近记录: |