出身背景

我正在使用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的所有用法!希望这对你有帮助!

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

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

readJsonFile() // prints your json object

使用fs extra包非常简单:

同步:

const fs = require('fs-extra')

const packageObj = fs.readJsonSync('./package.json')
console.log(packageObj.version) 

异步:

const fs = require('fs-extra')

const packageObj = await fs.readJson('./package.json')
console.log(packageObj.version) 

2022年答案,使用ES6模块语法和async/await

在现代JavaScript中,这可以作为一行代码完成,而无需安装其他包:

import { readFile } from 'fs/promises';

let data = JSON.parse(await readFile("filename.json", "utf8"));

根据需要添加try/catch块来处理异常。

在节点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
  })