Updating / Appending Files
Swipe to show menu
To add new content instead of replacing it, you can use:
fs.appendFileSync()
This method adds data to the end of the file.
Example
const fs = require('fs');
fs.appendFileSync('notes.txt', '\nSecond note');
\ncreates a new line;- The new note is added below the existing content.
Result in the File
First note
Second note
Each time you run this code, a new line will be added.
writeFileSync vs appendFileSync
It is important to understand the difference:
writeFileSync: replaces all content;appendFileSync: adds new content.
Example Comparison
// Overwrites file
fs.writeFileSync('notes.txt', 'New content');
// Appends to file
fs.appendFileSync('notes.txt', '\nAnother note');
When to Use Appending
Appending is useful when you want to:
- Store multiple records (like notes or logs);
- Keep history of actions;
- Add new data without losing old data.
Everything was clear?
Thanks for your feedback!
SectionΒ 1. ChapterΒ 23
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat
SectionΒ 1. ChapterΒ 23