0

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

1 Answer 1

3

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 writeFileSync to append the new text:

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

For more different flag values see here

Sign up to request clarification or add additional context in comments.

2 Comments

What is fileWriteSync? Did you mean writeFileSync?
@Betty oh didn't see that. Thank you for pointing out :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.