Suggest an editImprove this articleRefine the answer for “What does fs.watch() do?”. Your changes go to moderation before they’re published.Approval requiredContentWhat you’re changing🇺🇸EN🇺🇦UAPreviewTitle (EN)Short answer (EN)`fs.watch()` watches a file or folder and calls a callback with an event type (`rename` or `change`) whenever something changes; it doesn't read the file's content, only reports that a change happened. **Key point:** behavior depends on the OS (inotify on Linux, FSEvents on macOS, ReadDirectoryChangesW on Windows) and doesn't guarantee no event will ever be missed - for more reliable watching, the chokidar library is a better choice.Shown above the full answer for quick recall.Answer (EN)ImageIn Node.js, `fs.watch()` is used to **track changes in the filesystem**, it "watches" files or folders and calls a callback when something changes. ## Signature ```javascript fs.watch(filename[, options][, listener]) ``` ### Arguments: - `filename`, the path to the file or directory to watch. - `options` *(optional)*: - `persistent`: `true` by default, if `false`, the watch won't keep the Node.js process "alive"; - `recursive`: `true` watches all subdirectories recursively (macOS and Windows only); - `encoding`: the encoding for filenames (`'utf8'` by default). - `listener`, the callback invoked on changes. ## Example ```javascript const fs = require('fs'); fs.watch('./data', (eventType, filename) => { console.log(`Event: ${eventType}`); console.log(`File changed: ${filename}`); }); ``` Possible `eventType` values: - `"rename"`, a file was **renamed, created, or deleted**; - `"change"`, a file was **modified** (for example, its content was updated). ## A practical example Watching a config file for changes: ```javascript fs.watch('config.json', (eventType) => { if (eventType === 'change') { console.log('The config file was updated! Reloading settings...'); // For example, re-read the JSON here } }); ``` ## Quirks and limitations 1. **Behavior depends on the OS** Node.js uses the platform's native APIs: - `inotify` on Linux, - `FSEvents` on macOS, - `ReadDirectoryChangesW` on Windows. So events can differ slightly across platforms. 2. **Not every change is guaranteed to be caught**, especially when many files change at once. 3. `fs.watch()` **doesn't read the file's content**, it only reports **that** something changed. 4. For more reliable watching (with buffering and handling of missed events), the [**chokidar**](https://www.npmjs.com/package/chokidar) library is a better choice, it's cross-platform and more stable. ## Summary > `fs.watch()` is Node.js's built-in function for **watching files and folders for changes**. > It calls a callback on `"change"` or `"rename"` events, > and it's useful for things like: > > - automatically reloading configuration, > - rebuilding a project when files change, > - monitoring logs or directories.For the reviewerNote to the moderator (optional)Visible only to the moderator. Helps review go faster.