appendFile
- Node.js course
- Beginner
- Lesson 103/116
- 5 min
Learn to append to files with fs.appendFile.
What is appendFile?
fs.appendFile adds content to the end of a file. If the file does not exist it is created; if it exists the existing content is preserved and the new content is appended. Unlike writeFile, it does not delete the old content.
await fs.appendFile('log.txt', 'new line\n');Here 'new line' is appended to log.txt. If the file is missing it behaves like writeFile and creates it. It is ideal for logging; each new event is appended, old entries are kept.
Practice Your turn: append with appendFile
Start with import fs from 'fs/promises'. Define an async function run(). First write await fs.writeFile('log.txt', 'start'). Then append with await fs.appendFile('log.txt', ' end'). Read with const data = await fs.readFile('log.txt', 'utf8') and log with console.log(data). Call run().
Starter code
// Import fs/promises
// Define async function run
// Start with writeFile, append with appendFile, read with readFile
// Call runSample solution
import fs from 'fs/promises';
async function run() {
await fs.writeFile('log.txt', 'start');
await fs.appendFile('log.txt', ' end');
const data = await fs.readFile('log.txt', 'utf8');
console.log(data);
}
run();Expected output
start end
The logging pattern
A common use of appendFile is logging. Each event is appended to the file; old entries are kept, new ones are written at the end. This is ideal for server logs, error records and audit trails.
await fs.appendFile('server.log', 'request received\n');Here each request appends a new line to server.log. With \n each event goes on its own line; you can process the file line by line. To avoid clashes in parallel writes, it is important to write from a single process in order.
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What happens when fs.appendFile is called on an existing file?
- Old content is deleted
- It throws an error
- File size does not change
- New content is appended Correct answer
Explanation: appendFile keeps old content and adds to the end.
2 appendFile properties
| Term | Meaning |
|---|---|
appendFile |
appends to end |
writeFile |
overwrites |
log |
common use |
3 Fill in the blank: appendFile
await fs.____('log.txt', 'new line
');
await fs.appendFile('log.txt', 'new line
');
Explanation: appendFile adds to a file.