如何使用 fs.appendFile() 附加文件但不写入另一个 JSON 对象

How to append a file using fs.appendFile() but not write another JSON object

我正在尝试使用 fs.appendFile() 在我的 json 文件中写入键值对。

这是我的代码:

 router.post('/add', function(req, res) {
  var article = {
    title: req.body.title,
    content: req.body.content
  }

  var articleData = {};

  articleData[article.title] = article.content;

  var textData = JSON.stringify(articleData, null, 2);

  fs.appendFile('model/text.json', textData, 'utf8', finished);

  function finished () {
    console.log('Finished writing');
  }
});

但是在我的 text.json 文件中,我只得到这个:

{
  "test1": "test1"
}{
  "test2": "test2"
}

我无法像这样附加它:

{
    "test1": "test1",
    "test2": "test2"
}

首先您需要读取您的文件,然后处理 json 数据以将您的内容添加到其中。 你的第二步是写文件。你可以参考下面的例子。

fs.readFile('model/text.json', 'utf8', function readFileCallback(err, data){
    if (err){
        console.log(err);
    } else {
    objData = JSON.parse(data); //now it an object
    objData.test2 = 'test2'; //add/append desired data
    jsonData = JSON.stringify(objData); //convert it back to json
    fs.writeFile('model/text.json', jsonData, 'utf8', callback); // write it back 
}});