node.js 如何更新json文件中的值并通过node.js保存

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10685998/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 15:43:59  来源:igfitidea点击:

How to update a value in a json file and save it through node.js

jsonnode.js

提问by Nava Polak Onik

How do I update a value in a json file and save it through node.js? I have the file content:

如何更新 json 文件中的值并通过 node.js 保存它?我有文件内容:

var file_content = fs.readFileSync(filename);
var content = JSON.parse(file_content);
var val1 = content.val1;

Now I want to change the value of val1and save it to the file.

现在我想更改 的值val1并将其保存到文件中。

回答by Seth

Doing this asynchronously is quite easy. It's particularly useful if you're concerned for blocking the thread (likely).

异步执行此操作非常简单。如果您担心阻塞线程(可能),它特别有用。

const fs = require('fs');
const fileName = './file.json';
const file = require(fileName);

file.key = "new value";

fs.writeFile(fileName, JSON.stringify(file), function writeJSON(err) {
  if (err) return console.log(err);
  console.log(JSON.stringify(file));
  console.log('writing to ' + fileName);
});

The caveat is that json is written to the file on one line and not prettified. ex:

需要注意的是,json 是在一行上写入文件并且没有进行美化。前任:

{
  "key": "value"
}

will be...

将会...

{"key": "value"}

To avoid this, simply add these two extra arguments to JSON.stringify

为避免这种情况,只需将这两个额外的参数添加到 JSON.stringify

JSON.stringify(file, null, 2)

null- represents the replacer function. (in this case we don't want to alter the process)

null- 代表替换函数。(在这种情况下,我们不想改变流程)

2- represents the spaces to indent.

2- 表示要缩进的空格。

回答by Peter Lyons

//change the value in the in-memory object
content.val1 = 42;
//Serialize as JSON and Write it to a file
fs.writeFileSync(filename, JSON.stringify(content));

回答by satej sarker

addition to the previous answer add file path directory for the write operation

除了上一个答案之外,为写操作添加文件路径目录

 fs.writeFile(path.join(__dirname,jsonPath), JSON.stringify(newFileData), function (err) {}

回答by Apoorva Shah

// read file and make object
let content = JSON.parse(fs.readFileSync('file.json', 'utf8'));
// edit or add property
content.expiry_date = 999999999999;
//write file
fs.writeFileSync('file.json', JSON.stringify(content));