出身背景

我正在使用Node.js进行一些实验,希望将JSON对象从文本文件或.js文件(哪个更好??)读取到内存中,以便我可以从代码中快速访问该对象。我意识到有像蒙哥、阿尔弗雷德等这样的东西,但这不是我现在需要的。

问题

如何使用JavaScript/Node从文本或js文件中读取JSON对象并将其写入服务器内存?


当前回答

异步是有原因的!向@mihai扔石头

否则,以下是他在异步版本中使用的代码:

// Declare variables
var fs = require('fs'),
    obj

// Read the file and send to the callback
fs.readFile('path/to/file', handleFile)

// Write the callback function
function handleFile(err, data) {
    if (err) throw err
    obj = JSON.parse(data)
    // You can now play with your datas
}

其他回答

https://nodejs.org/dist/latest-v6.x/docs/api/fs.html#fs_fs_readfile_file_options_callback

var fs = require('fs');  

fs.readFile('/etc/passwd', (err, data) => {
  if (err) throw err;
  console.log(data);
});  

// options
fs.readFile('/etc/passwd', 'utf8', callback);

https://nodejs.org/dist/latest-v6.x/docs/api/fs.html#fs_fs_readfilesync_file_options

您可以在文件系统文档中找到Node.js的所有用法!希望这对你有帮助!

我找到的最简单的方法是只使用require和JSON文件的路径。

例如,假设您有以下JSON文件。

测试.json

{
  "firstName": "Joe",
  "lastName": "Smith"
}

然后,您可以使用require在node.js应用程序中轻松加载

var config = require('./test.json');
console.log(config.firstName + ' ' + config.lastName);

至少在Node v8.9.1中,您可以

var json_data=require('/path/to/local/file.json');

并访问JSON对象的所有元素。

function parseIt(){
    return new Promise(function(res){
        try{
            var fs = require('fs');
            const dirPath = 'K:\\merge-xml-junit\\xml-results\\master.json';
            fs.readFile(dirPath,'utf8',function(err,data){
                if(err) throw err;
                res(data);
        })}
        catch(err){
            res(err);
        }
    });
}

async function test(){
    jsonData = await parseIt();
    var parsedJSON = JSON.parse(jsonData);
    var testSuite = parsedJSON['testsuites']['testsuite'];
    console.log(testSuite);
}

test();

这么多答案,从来没有人做过比较同步与异步与需求的基准。我在这里描述了通过require、readFileSync和readFile在内存中读取json的不同用例。