Read json file content with require vs fs.readFile

前端 未结 7 2009
说谎
说谎 2020-11-30 03:46

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. Wh

7条回答
  •  醉话见心
    2020-11-30 04:16

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

提交回复
热议问题