How to Use fs.writeFile in Node.js: Simple Guide
Use
fs.writeFile in Node.js to write data to a file asynchronously by providing the file path, data, and a callback function that handles errors. It creates the file if it doesn't exist or overwrites it if it does.Syntax
The fs.writeFile function takes three main arguments: the file path as a string, the data to write (string or buffer), and a callback function that runs after the write completes or errors.
The callback receives an error object if something goes wrong, otherwise it means the write was successful.
javascript
fs.writeFile(path, data, callback)
Example
This example writes the text "Hello, Node.js!" to a file named greeting.txt. If the file doesn't exist, it will be created. If it exists, its content will be replaced.
javascript
import { writeFile } from 'fs'; writeFile('greeting.txt', 'Hello, Node.js!', (err) => { if (err) { console.error('Error writing file:', err); return; } console.log('File written successfully'); });
Output
File written successfully
Common Pitfalls
- Not handling the error in the callback can hide problems like permission issues or invalid paths.
- Using
fs.writeFilewill overwrite existing files without warning, so be careful if you want to append instead. - Passing non-string or non-buffer data without converting can cause unexpected results.
javascript
import { writeFile } from 'fs'; // Wrong: ignoring error writeFile('file.txt', 'data', () => {}); // Right: handle error writeFile('file.txt', 'data', (err) => { if (err) { console.error('Write failed:', err); } else { console.log('Write succeeded'); } });
Quick Reference
Remember these tips when using fs.writeFile:
- It is asynchronous and non-blocking.
- Always handle errors in the callback.
- It overwrites files by default.
- Use
Bufferorstringdata types.
Key Takeaways
Use fs.writeFile to write or overwrite files asynchronously in Node.js.
Always check for errors in the callback to catch write failures.
fs.writeFile replaces existing file content without warning.
Data must be a string or buffer; convert other types before writing.
This method is non-blocking and runs in the background.