Read json file content with require vs fs.readFile

匿名 (未验证) 提交于 2019-12-03 01:23:02

问题:

Suppose that for every response from an API, i need to map the value from the response to an existing json file in my web application and display the value from the json. What are the better approach in this case to read the json file? require or fs.readfile. Note that there might be thousands of request comes in at a same time.

Note that I do not expect there is any changes to the file during runtime.

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 });

回答1:

I suppose you'll JSON.parse the json file for the comparison, in that case, require is better because it'll parse the file right away and it's sync:

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

If you have thousands of request using that file, require it once outside your request handler and that's it:

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 });


回答2:

There are two versions for fs.readFile, and they are

Asynchronous version

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

Synchronous version

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

To use require to parse json file as below

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

But, note that

  • require is synchronous and only reads the file once, following calls return the result from cache

  • If your file does not have a .json extension, require will not treat the contents of the file as JSON.



回答3:

Use node-fixtures if dealing with JSON fixtures in your tests.

The project will look for a directory named fixtures which must be child of your test directory in order to load all the fixtures (*.js or *.json files):

// 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" 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!