How to Write a File in Node.js: Simple Guide
In Node.js, you can write a file using the
fs.writeFile or fs.writeFileSync methods from the built-in fs module. fs.writeFile writes files asynchronously, while fs.writeFileSync does it synchronously blocking the code until done.Syntax
The fs.writeFile method writes data to a file asynchronously. It takes the file path, data to write, optional options, and a callback function that runs after writing completes or errors.
The fs.writeFileSync method does the same but blocks the program until the file is written, returning immediately or throwing an error.
javascript
import { writeFile, writeFileSync } from 'fs'; // Asynchronous syntax writeFile(path, data, options, callback); // Synchronous syntax writeFileSync(path, data, options);
Example
This example shows how to write a text file asynchronously and synchronously. The asynchronous version logs a message when done, while the synchronous version blocks until finished.
javascript
import { writeFile, writeFileSync } from 'fs'; // Asynchronous write writeFile('example.txt', 'Hello from async write!', { encoding: 'utf8' }, (err) => { if (err) { console.error('Async write failed:', err); } else { console.log('Async write completed'); } }); // Synchronous write try { writeFileSync('example-sync.txt', 'Hello from sync write!', { encoding: 'utf8' }); console.log('Sync write completed'); } catch (err) { console.error('Sync write failed:', err); }
Output
Async write completed
Sync write completed
Common Pitfalls
- Forgetting to handle errors in the callback of
fs.writeFilecan cause silent failures. - Using synchronous writes (
writeFileSync) in a server environment can block other operations and reduce performance. - Not specifying encoding (like 'utf8') can lead to unexpected file content.
javascript
import { writeFile } from 'fs'; // Wrong: no error handling writeFile('bad.txt', 'data'); // Right: handle error writeFile('good.txt', 'data', { encoding: 'utf8' }, (err) => { if (err) { console.error('Write failed:', err); } else { console.log('Write succeeded'); } });
Quick Reference
Here is a quick summary of key points when writing files in Node.js:
| Method | Description | Use Case |
|---|---|---|
| fs.writeFile(path, data, options, callback) | Writes file asynchronously | Preferred for non-blocking operations |
| fs.writeFileSync(path, data, options) | Writes file synchronously | Use for scripts or startup tasks |
| options.encoding | Encoding of file content | Usually 'utf8' for text files |
| callback(err) | Function called after async write | Check for errors here |
Key Takeaways
Use fs.writeFile for non-blocking asynchronous file writes with error handling.
Use fs.writeFileSync only when blocking behavior is acceptable, like in scripts.
Always specify encoding like 'utf8' when writing text files.
Handle errors in callbacks to avoid silent failures.
Avoid synchronous writes in servers to keep performance smooth.