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

  1. Import fs: const fs = require('fs');.
  2. Write asynchronously: fs.writeFile('output.txt', 'Hello', 'utf8', (err) => { ... });.
  3. Write synchronously: fs.writeFileSync('output.txt', 'Hello');.
  4. Append to a file with fs.appendFile('log.txt', 'entry\n', callback);.
  5. Use the flag option (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.
  • EACCES errors indicate permission issues; ensure the process has write access to the directory.