我正在尝试使用Node和Express来建立一个笔记应用程序。现在,保存的所有注释都将覆盖db.json文件中的内容。我正在尝试将db.json中已有的内容推送到一个空数组,推送最新的注释,然后使用该最终数组写入文件。有人对我在这里做错的事情有任何提示吗?谢谢。
read() {
return readFileAsync(path.join(__dirname, "db.json"), "utf8");
}
write(note) {
return writeFileAsync(path.join(__dirname, "db.json"), JSON.stringify(note))
}
getNotes() {
return this.read().then(notes => {
var notesObject = JSON.parse(notes);
});
}
addNote(note) {
const newNoteArray = [];
const { title, text } = note;
if (!title || !text) {
throw new Error("Note 'title' and 'text' cannot be blank");
}
const newNote = { title, text, id: uuidv1() };;
return this.getNotes()
.then(notes => {
newNoteArray.push(notes);;
})
.then(newNoteArray.push(newNote))
.then(this.write(newNoteArray));
}
没有看到writeFileAsync
函数的内容,我无法给出确切的答案,但是问题是您很可能会覆盖文件内容,而不是附加文件内容。 check out this quick tutorial on how to write and append contents to a file
尝试一下:
addNote(note) {
const { title, text } = note;
if (!title || !text) {
throw new Error("Note 'title' and 'text' cannot be blank");
}
const newNote = { title, text, id: uuidv1() };
return this.getNotes()
.then(notes => {
const newNoteArray = JSON.parse(notes);
newNoteArray.push(newNote);
return this.write(newNoteArray);
})
}
麻烦的是,notes
是作为参数提供的,但这是文件的未解析内容。因此,您需要将其解析为newNoteArray
,然后按下newNote
,然后将其写出。