我正在尝试使用 fs.writeFileSync('notes.json', originalNoteString) 写入文件。当我第一次运行该程序时,它会附加,但当我第二次运行该程序时,它不会再次附加。谁能帮我看看这里发生了什么。
const fs = require('fs');
let orginalNote = {
title: 'sometitle',
body: 'somebody'
}
let originalNoteString = JSON.stringify(orginalNote);
fs.writeFileSync('notes.json', originalNoteString);
let noteString = fs.readFileSync('notes.json');
let note = JSON.parse(noteString);
console.log(typeof note);
console.log(note.title);
最佳答案
fs.writeFileSync
的默认模式是覆盖整个文件。正如 @Bartosz Gościński 提到的,您可以使用 appendFileSync
或者设置 option在 fileWriteSync
中附加新文本:
fs.writeFileSync('notes.json', originalNoteString, {flag: 'a'});
有关更多不同的标志值,请参阅 here
关于javascript - 使用 fs.writefilesync 写入 NodeJS 中的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52392818/