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

Files को Watch करना

fs.watch आपको बताता है जब एक file या folder बदलता है ताकि आप automatically react कर सकें।

In this page:

  1. Files Watch करना
Syntax
javascript
fs.watch('path', (eventType, filename) => {
  // handle change or rename
});

Files Watch करना

fs.watch(path, listener) change और rename events emit करता है, और fs.watchFile changes के लिए poll करता है। Behaviour platform से अलग होता है और events कई बार fire हो सकते हैं, इसलिए इन्हें debounce करें। nodemon जैसे tools इस पर built हैं।

Note: watch handlers debounce करें क्योंकि एक save कई events trigger कर सकता है।

उदाहरण: 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/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. platforms के आर-पार identical events पर depend करना
  2. watcher close न करना
  3. duplicate events handle करना
चैप्टर सारांश
  • fs.watch changes report करता है
  • Events repeat हो सकते हैं
  • Handlers debounce करें
  • काम खत्म होने पर watchers close करें
🔒

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.