简体   繁体   English

使用fs.writefilesync在Node.js中写入文件

[英]Writing into file in nodejs using fs.writefilesync

I am trying to write into a file using fs.writeFileSync('notes.json', originalNoteString) . 我正在尝试使用fs.writeFileSync('notes.json',originalNoteString)写入文件。 When I run the program first time it is appending but when I run the program second time it is not appending again. 当我第一次运行该程序时,它是追加的,但是当我第二次运行该程序时,它是不会追加的。 Can Anyone help me what is happening here. 有人可以帮我这里发生什么吗?

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);

The default mode of fs.writeFileSync is overwrite the complete file. fs.writeFileSync的默认模式是覆盖整个文件。 As @Bartosz Gościński mentioned you can use appendFileSync or you set an option in fileWriteSync to append the new text: 作为@BartoszGościński提到你可以使用appendFileSync或者你设置的选项,fileWriteSync追加新的文本:

fs.writeFileSync('notes.json', originalNoteString, {flag: 'a'});

For more different flag values see here 有关更多不同的标志值,请参见此处

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM