To write to files in Node.js, use the fs
(File System) module. Here are the key methods with examples:
1. fs.writeFile()
(Asynchronous – Non-Blocking)
Writes data to a file, replacing it if it exists.
const fs = require('fs');
// Basic write (UTF-8 encoding)
fs.writeFile('file.txt', 'Hello World', (err) => {
if (err) throw err;
console.log('File saved!');
});
// With options (append instead of overwrite)
fs.writeFile('log.txt', 'New log entry\n', { flag: 'a' }, (err) => {
if (err) throw err;
});
2. fs.writeFileSync()
(Synchronous – Blocking)
Synchronous version of writeFile
:
const fs = require('fs');
try {
fs.writeFileSync('sync-file.txt', 'Blocking write');
console.log('File saved synchronously');
} catch (err) {
console.error(err);
}
3. fs.appendFile()
(Append Content Asynchronously)
Adds content to the end of a file:
const fs = require('fs');
fs.appendFile('notes.txt', 'New note\n', (err) => {
if (err) throw err;
console.log('Note appended');
});
4. fs.createWriteStream()
(Stream for Large Files)
Efficient for writing large datasets incrementally:
const fs = require('fs');
const stream = fs.createWriteStream('bigfile.txt', { flags: 'a' });
stream.write('Chunk 1\n');
stream.write('Chunk 2\n');
stream.end(() => console.log('Stream finished'));
// Handle errors
stream.on('error', (err) => console.error('Stream error:', err));
5. fs.promises.writeFile()
(Promise-Based API)
Modern async/await syntax:
const fs = require('fs/promises');
async function saveData() {
try {
await fs.writeFile('data.json', JSON.stringify({ key: 'value' }));
console.log('Data saved');
} catch (err) {
console.error('Error:', err);
}
}
saveData();
Flags for File Operations
Flag | Description |
---|---|
w | Overwrite (default for writeFile ) |
a | Append to file |
wx | Write only if file doesn’t exist |
r+ | Read and write |
Key Notes
- Encoding
Specify encoding in options (e.g.,{ encoding: 'utf8' }
). Default is UTF-8. - Error Handling
Always handle errors in callbacks or usetry/catch
for synchronous code. - Performance
- Use streams for large files to avoid memory overload.
- Prefer asynchronous methods for non-blocking operations.
Full Example: Write & Append
const fs = require('fs');
// Write initial file
fs.writeFile('example.txt', 'Start of log\n', (err) => {
if (err) throw err;
// Append after initial write
fs.appendFile('example.txt', 'Log entry 1\n', (err) => {
if (err) throw err;
console.log('Log updated');
});
});
Comparison Table
Method | Use Case | Async/Sync |
---|---|---|
writeFile() | Simple writes, small files | Async |
writeFileSync() | Scripts needing blocking I/O | Sync |
appendFile() | Adding to logs or existing files | Async |
createWriteStream() | Large files (e.g., videos, CSVs) | Async |