How to Append to File in Node.js: Simple Guide
In Node.js, you can append data to a file using
fs.appendFile for asynchronous writing or fs.appendFileSync for synchronous writing. These methods add new content to the end of the file without overwriting existing data.Syntax
The fs.appendFile method appends data to a file asynchronously, while fs.appendFileSync does it synchronously. Both take the file path, data to append, optional options, and a callback (for async).
- file: Path to the file.
- data: The string or buffer to add.
- options: Optional encoding or mode.
- callback: Function called after async append completes.
javascript
const fs = require('fs'); // Asynchronous append fs.appendFile(path, data[, options], callback); // Synchronous append fs.appendFileSync(path, data[, options]);
Example
This example shows how to append text to a file named notes.txt asynchronously and then synchronously. It demonstrates adding new lines without erasing existing content.
javascript
const fs = require('fs'); const filePath = 'notes.txt'; const textToAdd = '\nAppended line using appendFile.'; // Asynchronous append fs.appendFile(filePath, textToAdd, 'utf8', (err) => { if (err) { console.error('Error appending asynchronously:', err); } else { console.log('Async append done.'); // Synchronous append after async completes try { fs.appendFileSync(filePath, '\nAppended line using appendFileSync.', 'utf8'); console.log('Sync append done.'); } catch (err) { console.error('Error appending synchronously:', err); } } });
Output
Async append done.
Sync append done.
Common Pitfalls
Common mistakes include:
- Not handling errors in the callback, which can hide problems.
- Using synchronous methods in performance-critical or server code, which blocks the event loop.
- Forgetting to add newline characters if you want each append on a new line.
Always prefer asynchronous fs.appendFile in most cases to keep your app responsive.
javascript
const fs = require('fs'); // Wrong: ignoring errors fs.appendFile('file.txt', 'data'); // No callback, no error handling // Right: handle errors fs.appendFile('file.txt', 'data', (err) => { if (err) console.error('Append error:', err); else console.log('Append success'); });
Quick Reference
| Method | Description | Use Case |
|---|---|---|
| fs.appendFile(path, data, callback) | Asynchronously appends data to a file | Preferred for non-blocking file writes |
| fs.appendFileSync(path, data) | Synchronously appends data to a file | Use for scripts or startup tasks |
| Error Handling | Always check errors in callback or try-catch | Avoid silent failures |
| Newline | Add '\n' if you want new lines | Keep file content readable |
Key Takeaways
Use fs.appendFile for non-blocking, asynchronous file appends.
Always handle errors in the callback to catch problems.
Add newline characters explicitly to separate appended content.
Avoid fs.appendFileSync in performance-sensitive code to prevent blocking.
Appending adds data to the end without overwriting existing file content.