出身背景

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

问题

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


当前回答

在节点8中,可以使用内置的util.provisify()异步读取如下文件

const {promisify} = require('util')
const fs = require('fs')
const readFileAsync = promisify(fs.readFile)

readFileAsync(`${__dirname}/my.json`, {encoding: 'utf8'})
  .then(contents => {
    const obj = JSON.parse(contents)
    console.log(obj)
  })
  .catch(error => {
    throw error
  })

其他回答

使用节点fs extra(异步等待)

const readJsonFile = async () => {
    const myJsonObject = await fs.readJson('./my_json_file.json');
    console.log(myJsonObject);
}

readJsonFile() // prints your json object

异步是有原因的!向@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
}

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

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

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

测试.json

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

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

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

在节点8中,可以使用内置的util.provisify()异步读取如下文件

const {promisify} = require('util')
const fs = require('fs')
const readFileAsync = promisify(fs.readFile)

readFileAsync(`${__dirname}/my.json`, {encoding: 'utf8'})
  .then(contents => {
    const obj = JSON.parse(contents)
    console.log(obj)
  })
  .catch(error => {
    throw error
  })