简体   繁体   中英

Writing into file in nodejs using fs.writefilesync

I am trying to write into a file using 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. As @Bartosz Gościński mentioned you can use appendFileSync or you set an option in fileWriteSync to append the new text:

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

For more different flag values see here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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