Node.js 添加到JSON的新数据不断替换以前的数据
我的代码中的“notes=JSON.parse(fs.readFileSync(“notes data.JSON”))”行似乎没有正常工作 当我添加新注释时,它应该添加到.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
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”)//