Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 添加到JSON的新数据不断替换以前的数据_Node.js_Json - Fatal编程技术网

Node.js 添加到JSON的新数据不断替换以前的数据

Node.js 添加到JSON的新数据不断替换以前的数据,node.js,json,Node.js,Json,我的代码中的“notes=JSON.parse(fs.readFileSync(“notes data.JSON”))”行似乎没有正常工作 当我添加新注释时,它应该添加到.json文件中的数组中,但它只是替换了以前的注释 let addNote = (title, body) => { let notes = []; let note = { title, body }; notes.push(note); fs.writeFileSync("notes

我的代码中的“notes=JSON.parse(fs.readFileSync(“notes data.JSON”))”行似乎没有正常工作

当我添加新注释时,它应该添加到.json文件中的数组中,但它只是替换了以前的注释

let addNote = (title, body) => {
  let notes = [];
  let note = {
    title,
    body
  };
  notes.push(note);
  fs.writeFileSync("notes-data.json", JSON.stringify(notes));
  notes = JSON.parse(fs.readFileSync("notes-data.json"))
};
代码截图:


提前感谢您

如果您想添加到文件内容中,那么您应该在执行任何其他操作之前阅读内容:

let addNote = (title, body) => {
  let notes;
  try {
      notes = JSON.parse(fs.readFileSync("notes-data.json")); // <---
  } catch(e) {
      notes = [];
  }
  let note = {
    title,
    body
  };
  notes.push(note);
  fs.writeFileSync("notes-data.json", JSON.stringify(notes));
};
let addNote=(标题、正文)=>{
记笔记;
试一试{

notes=JSON.parse(fs.readFileSync(“notes data.JSON”);//如果要添加到文件内容中,那么您应该在执行任何其他操作之前真正读取内容:

let addNote = (title, body) => {
  let notes;
  try {
      notes = JSON.parse(fs.readFileSync("notes-data.json")); // <---
  } catch(e) {
      notes = [];
  }
  let note = {
    title,
    body
  };
  notes.push(note);
  fs.writeFileSync("notes-data.json", JSON.stringify(notes));
};
let addNote=(标题、正文)=>{
记笔记;
试一试{
notes=JSON.parse(fs.readFileSync(“notes data.JSON”)//