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 objectvar 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
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):