在node.js中如何读写JSON文件

4

我对node.js还比较陌生,想知道是否可以读写JSON文件。我正在尝试创建一个易于访问的惩罚历史记录,理想情况下希望能够创建类似以下方式的东西:

{
"punishments": {
    "users": {
      "<example user who has a punishment history>": {
        "punishment-1567346": {
          "punishment-id": "1567346",
          "punishment-type": "mute",
          "punishment-reason": "<reason>"
        },
        "punishment-1567347": {
          "punishment-id": "1567347",
          "punishment-type": "ban",
          "punishment-reason": "<reason>"
        }
      }
    }
  }
}

我希望能够找到一种方法来访问格式化的惩罚历史记录。但实际上,我不知道该从哪里开始。


这里有一篇非常详细的关于此的文章:https://stackabuse.com/reading-and-writing-json-files-with-node-js/ - Tony Drummond
@thanhdx - 上下文错误 - 不是来自浏览器,而是来自NodeJS。 - Randy Casburn
@RandyCasburn 是的,我刚刚重新设置了标志。抱歉。 - thanhdx
这里有更好的答案:https://stackoverflow.com/questions/42671321/how-to-write-update-new-json-file-with-nodejs - Randy Casburn
3个回答

19

你可以使用 Node.js 内置的 fs 库进行读写操作。

步骤 #1 - 导入 fs

const fs = require('fs');

第 2 步 - 读取文件

let rawdata = fs.readFileSync('punishmenthistory.json');
let punishments= JSON.parse(rawdata);
console.log(punishments);

现在您可以使用punishments变量来检查JSON文件中的数据。同时,您也可以更改数据,但目前只驻留在变量中。

第三步 - 写入文件

let data = JSON.stringify(punishments);
fs.writeFileSync('punishmenthistory.json', data);

完整代码:

const fs = require('fs');

let rawdata = fs.readFileSync('punishmenthistory.json');
let punishments= JSON.parse(rawdata);
console.log(punishments);

let data = JSON.stringify(punishments);
fs.writeFileSync('punishmenthistory.json', data);

References: https://stackabuse.com/reading-and-writing-json-files-with-node-js/


2

使用NodeJS文件系统https://nodejs.org/dist/latest-v14.x/docs/api/fs.html

这里我使用了writeFileSync API来写入文件,readFileSync来从文件中读取。同时,在写入时不要忘记JSON.stringify(data),因为你正在将数据写入JSON文件。

const fs = require("fs");
const path = require("path");

// Write Data
const data = {
"punishments": {
    "users": {
      "<example user who has a punishment history>": {
        "punishment-1567346": {
          "punishment-id": "1567346",
          "punishment-type": "mute",
          "punishment-reason": "<reason>"
        },
        "punishment-1567347": {
          "punishment-id": "1567347",
          "punishment-type": "ban",
          "punishment-reason": "<reason>"
        }
      }
    }
  }
};

fs.writeFileSync(path.join(__dirname, "outputfilepath", "outputfile.json"), JSON.stringify(data), "utf8");

// Read data
const rData = fs.readFileSync(path.join(__dirname, "outputfilepath", "outputfile.json"), "utf8");
const jsonData = JSON.parse(rData);

以下是工作示例, https://repl.it/repls/OutrageousInbornBruteforceprogramming#index.js


2
您可以像这样进行阅读:
您可以通过以下方式进行阅读:
const fs = require('fs')
function jsonReader(filePath, cb) {
    fs.readFile(filePath, (err, fileData) => {
        if (err) {
            return cb && cb(err)
        }
        try {
            const object = JSON.parse(fileData)
            return cb && cb(null, object)
        } catch(err) {
            return cb && cb(err)
        }
    })
}
jsonReader('./customer.json', (err, customer) => {
    if (err) {
        console.log(err)
        return
    }
    console.log(customer.address) // => "Infinity Loop Drive"
})

并且像这样书写:

const fs = require('fs')
const customer = {
    name: "Newbie Co.",
    order_count: 0,
    address: "Po Box City",
}
const jsonString = JSON.stringify(customer)
fs.writeFile('./newCustomer.json', jsonString, err => {
    if (err) {
        console.log('Error writing file', err)
    } else {
        console.log('Successfully wrote file')
    }
})

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接