Appending to Files with fs.appendFile()
You'll learn how to add content to the end of existing files without erasing what's already there.
The Core Idea
Sometimes you need to add data to a file rather than replace it entirely. Think of a logbook: you don't rewrite the entire book each time you add an entry—you simply flip to a new page and write. That's exactly what fs.appendFile() does in Node.js.
Unlike fs.writeFile(), which overwrites the entire file content, fs.appendFile() adds your new data to the end of an existing file. If the file doesn't exist yet, it creates one for you.
Basic Usage
const fs = require('fs');
fs.appendFile('log.txt', 'New log entry\n', (err) => {
if (err) {
console.error('Error appending to file:', err);
} else {
console.log('Content appended successfully');
}
});
This adds "New log entry" to the end of log.txt without touching any existing content.
Multiple Appends
You can call fs.appendFile() multiple times, and each call adds to the file:
fs.appendFile('data.txt', 'First line\n', (err) => {
if (err) throw err;
});
fs.appendFile('data.txt', 'Second line\n', (err) => {
if (err) throw err;
});
Common Use Cases
- Logging: Adding timestamped entries to log files
- Data collection: Appending records as they arrive
- Incremental file building: Adding sections to a report over time
Key Takeaway: fs.appendFile() safely adds content to the end of files without overwriting existing data, perfect for logs and incremental updates.