出身背景

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

问题

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


当前回答

使用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) 

其他回答

使用v8导入断言回答2022

import jsObject from "./test.json" assert { type: "json" };
console.log(jsObject)

动态导入

const jsObject = await import("./test.json", {assert: { type: "json" }});
console.log(jsObject);

更多信息请访问:v8导入断言

异步是有原因的!向@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的所有用法!希望这对你有帮助!

如果您正在寻找异步加载JSON文件的完整解决方案,请使用错误处理从相对路径加载JSON文件

  // Global variables
  // Request path module for relative path
    const path = require('path')
  // Request File System Module
   var fs = require('fs');


// GET request for the /list_user page.
router.get('/listUsers', function (req, res) {
   console.log("Got a GET request for list of users");

     // Create a relative path URL
    let reqPath = path.join(__dirname, '../mock/users.json');

    //Read JSON from relative path of this file
    fs.readFile(reqPath , 'utf8', function (err, data) {
        //Handle Error
       if(!err) {
         //Handle Success
          console.log("Success"+data);
         // Parse Data to JSON OR
          var jsonObj = JSON.parse(data)
         //Send back as Response
          res.end( data );
        }else {
           //Handle Error
           res.end("Error: "+err )
        }
   });
})

目录结构:

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