← Back to Node.js Course | Chapter 5: File System | Lesson 6 of 7

Watching files

fs.watch tells you when a file or folder changes so you can react automatically.

In this page:

  1. Watching files
Syntax
javascript
fs.watch('path', (eventType, filename) => {
  // handle change or rename
});

Watching files

fs.watch(path, listener) emits change and rename events, and fs.watchFile polls for changes. Behaviour differs by platform and events can fire multiple times, so debounce them. Tools like nodemon are built on this.

Note: Debounce watch handlers because one save can trigger several events.

Example: Watching files

javascript
const fs = require("fs");
fs.writeFileSync("watched.txt", "v1");
const watcher = fs.watch("watched.txt", (event) => {
  console.log("event:", event);
  watcher.close();
});
setTimeout(() => fs.writeFileSync("watched.txt", "v2"), 20);

// Output:
// event: change

⚠️ Run this in your own terminal or Node.js environment.

Related Topics
Common Mistakes
  1. Relying on identical events across platforms
  2. Not closing the watcher
  3. Handling duplicate events
Chapter Summary
  • fs.watch reports changes
  • Events may repeat
  • Debounce handlers
  • Close watchers when done
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.