03 / 16

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

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

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

Scenario Questions

0-2 years experience
  1. 1

    How would you write a JSON config object to a file called config.json?

  2. 2

    What happens if you call fs.writeFile on a path that's actually a directory?

  3. 3

    Why might you use writeFileSync in a CLI startup script instead of the async version?

2-5 years experience
  1. 1

    You'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. 2

    A teammate used fs.writeFileSync inside an Express route handler. Why is that problematic under load?

  3. 3

    How would you implement atomic writes so a reader never sees a half-written file?

5-8 years experience
  1. 1

    Design a file-based cache that handles concurrent writes from multiple worker processes without corruption.

  2. 2

    Your service streams large CSV exports to disk. Users report memory spikes during export. How do you fix it?

  3. 3

    How would you implement log rotation (daily files, max 30 days) without losing log entries during the rotation moment?

8+ years experience
  1. 1

    We're migrating from local filesystem writes to S3. How do you design the abstraction layer so callers don't change?

  2. 2

    Multiple services write to a shared NFS mount. How do you prevent corruption and ensure consistency?

  3. 3

    Design 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?