03 / 16

Explain how to write to a file in Node.js?

Difficulty: 2/10
fs module, async vs sync, streams

You can write to a file in Node.js using the fs.writeFile() method. Here's an example:

javascript

Scenario Questions

0-2 years experience

  1. 1How would you write a JSON config object to a file called config.json?
  2. 2What happens if you call fs.writeFile on a path that's actually a directory?
  3. 3Why might you use writeFileSync in a CLI startup script instead of the async version?

2-5 years experience

  1. 1You're adding a request logger that appends to a file. The app crashes and the last few log lines are missing. What went wrong?
  2. 2A teammate used fs.writeFileSync inside an Express route handler. Why is that problematic under load?
  3. 3How would you implement atomic writes so a reader never sees a half-written file?

5-8 years experience

  1. 1Design a file-based cache that handles concurrent writes from multiple worker processes without corruption.
  2. 2Your service streams large CSV exports to disk. Users report memory spikes during export. How do you fix it?
  3. 3How would you implement log rotation (daily files, max 30 days) without losing log entries during the rotation moment?

8+ years experience

  1. 1We're migrating from local filesystem writes to S3. How do you design the abstraction layer so callers don't change?
  2. 2Multiple services write to a shared NFS mount. How do you prevent corruption and ensure consistency?
  3. 3Design a write-ahead log for a custom embedded database engine — durability, recovery, and compaction.

Follow-up Questions

  • What happens if the file doesn't exist?
  • How would you handle writing a 10GB file?
  • When would you choose sync over async?
Share

Share via WhatsApp, X, Facebook, LinkedIn or copy link. Open Graph preview enabled.