How to write files using the fs module
· Category: Node.js
Short answer
Use fs.writeFile() to write data to a file asynchronously, fs.writeFileSync() for synchronous writes, or fs.promises.writeFile() with async/await.
Steps
- Import fs:
const fs = require('fs');. - Write asynchronously:
fs.writeFile('output.txt', 'Hello', 'utf8', (err) => { ... });. - Write synchronously:
fs.writeFileSync('output.txt', 'Hello');. - Append to a file with
fs.appendFile('log.txt', 'entry\n', callback);. - Use the
flagoption (w,a,wx) to control overwrite and creation behavior.
Tips
- Use
fs.mkdirSync(path, { recursive: true })before writing if the target directory may not exist. - For high-frequency writes, accumulate data in memory and flush periodically or use write streams.
Common issues
- Writing without proper error handling can lead to silent failures in production.
EACCESerrors indicate permission issues; ensure the process has write access to the directory.