将文本追加到现有的json文件node

将文本追加到现有的json文件node

本文介绍了将文本追加到现有的json文件node.js的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试向现有的json文件中添加新文本,我尝试了writeFileSync和appendFileSync,但是即使我使用JSON.stringify,添加的文本也无法格式化为json.

I'm trying to add a new text to an existing json file, I tried writeFileSync and appendFileSync however the text added doesn't format as json even when i use JSON.stringify.

const fs = require('fs');

fs.readFile("test.json", (err, data) => {
  if( err) throw err;

  var data = JSON.parse(data);
  console.log(data);
});

var student = {
  age: "23"
};

fs.appendFileSync("test.json", "age: 23");
// var writeData = fs.writeFileSync("test.json", JSON.stringify(student));

我的json文件

{ name: "kevin" }

Append结果如下:{name:"kevin"} age:"23"并且writeFileSync的结果类似于{name:"kevin"} {age:"23"}

Append turns out like this, {name: "kevin"}age: "23"and writeFileSync turns out like {name: "kevin"}{age: "23"}

我想要的是像这样连续向我的json文件中添加文本

What I want is to continuously add text to my json file like so

{
  name: "kevin",
  age: "23"
}

推荐答案

首先,不要使用readFileSyncwriteFileSync.它们阻止执行,并违反了node.js标准.这是正确的代码:

First, dont use readFileSync and writeFileSync. They block the execution, and go against node.js standards. Here is the correct code:

const fs = require('fs');

fs.readFile("test.json", (err, data) => {  // READ
    if (err) {
        return console.error(err);
    };

    var data = JSON.parse(data.toString());
    data.age = "23"; // MODIFY
    var writeData = fs.writeFile("test.json", JSON.stringify(data), (err, result) => {  // WRITE
        if (err) {
            return console.error(err);
        } else {
            console.log(result);
            console.log("Success");
        }

    });
});

此代码的作用:

  1. 从文件中读取数据.
  2. 修改数据以获取文件应具有的新数据.
  3. 将数据(附加)写回到文件中.
  1. Reads the data from the file.
  2. Modifies the data to get the new data the file should have.
  3. Write the data(NOT append) back to the file.

这篇关于将文本追加到现有的json文件node.js的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 14:05