skip to content

A Node.js dev tool calls fs.watch(dir, { recursive: true }); why does it behave differently on Linux, macOS and in containers, and what do you design around?

level: seniorimportance: nice to knowfreq 22%

answer

  1. one API, several kernel backends
  2. recursive is emulated on Linux
  3. the watch follows an inode
  4. events are hints, not a diff

basics

~20 s

fs.watch wraps each OS's notification API, so behaviour differs. On Linux Node emulates recursive watching with one watcher per file and directory; filenames can be null, replaced files go silent, and mounted volumes may report nothing. Treat events as hints.

solid answer

~50 s

`fs.watch` uses inotify on Linux, kqueue and FSEvents on macOS and `ReadDirectoryChangesW` on Windows, and the docs say it is not 100% consistent across platforms. `recursive: true` is native on macOS and Windows; on Linux, supported since v19.1.0, Node walks the tree itself with synchronous reads and opens a watcher per file and directory, so a large tree is slow to start and uses kernel watch resources. Node 24.14.0 added an `ignore` option, which that walker uses to skip paths such as `node_modules`. Events are only `'rename'` or `'change'`, `filename` may be `null`, and a watched file replaced by a rename leaves the watch on the old inode. On network shares and container host mounts, events can be missing, so fall back to `fs.watchFile` polling. Debounce events, re-read state on each one, and never treat them as an exact change log.

code

javascript · 19 lines
javascript
import { watch } from 'node:fs';
import path from 'node:path';

const ac = new AbortController();
const skipped = (name) => name.split(path.sep).some((part) => part === 'node_modules' || part === '.git');
let timer;

watch('src', { recursive: true, ignore: skipped, signal: ac.signal },
  (eventType, filename) => {
    // filename may be null; the event is only a hint to rescan
    clearTimeout(timer);
    timer = setTimeout(() => rebuild(filename ?? 'src'), 100);
  });

function rebuild(hint) {
  console.log('change near', hint, '- rescanning');
}

process.once('SIGINT', () => ac.abort());

go deeper

for a junior

Recall that fs.watch reports 'rename' and 'change' events, that the filename can be null, and that a watcher keeps the process running until closed.

for a middle

Explain the per-platform backends, why watching a file loses track after an atomic save, and when fs.watchFile polling is the fallback.

for a senior

Diagnose watchers that stall on Linux or in containers: emulated recursion, kernel watch exhaustion and missing events on mounts, and fix them with ignore, debouncing and rescans.

for a principal

Decide whether team tooling depends on native watching at all, or standardises on polling or rescans for container and network setups where notifications are not trustworthy.

## One API over several kernel mechanisms `fs.watch(filename, options, listener)` asks the operating system to notify the process when a file or directory changes. Node does not poll; it relies on each platform's own facility: | Platform | Backend used by `fs.watch` | `recursive: true` | |---|---|---| | Linux | inotify | emulated by Node, supported since v19.1.0 | | macOS | kqueue for files, FSEvents for directories | native | | Windows | `ReadDirectoryChangesW` | native | The documentation opens its caveats with the summary that matters: the API is **not 100% consistent across platforms** and is unavailable in some situations. A tool that works on one developer's laptop can misbehave on a colleague's Linux workstation or in a container. ## Recursive watching on Linux Because inotify does not watch subtrees, Node 24 implements `recursive: true` on Linux in JavaScript. Reading that implementation shows the cost: - At start it walks the tree with **`readdirSync` and `statSync`**, blocking the event loop for the length of the walk. - It opens **one underlying watcher for every file and directory** it finds, each consuming a kernel watch. - When a new directory appears, it walks and watches that too. On a repository with a full `node_modules`, startup is slow and the kernel's per-user watch limit can be exhausted. Node 24.14.0 added the **`ignore` option** (glob strings, a `RegExp`, a function, or an array of them); the Linux walker skips ignored paths entirely instead of watching and then filtering. On macOS and Windows a single native watch covers the tree, and ignored names are only filtered from the events. ## What an event does and does not tell you - **Two event types.** The listener receives `eventType`, either `'rename'` (on most platforms, a name appeared or disappeared) or `'change'`. - **The filename is optional.** It is provided only on Linux, macOS, Windows and AIX, and even there it is not guaranteed; code must handle `null`. - **The watch follows an inode.** On Linux and macOS `fs.watch` resolves the path to an inode and watches that. If the file is deleted and recreated, the watch reports the delete and keeps watching the **original** inode; the new file produces no events. Editors that save by writing a new file and renaming it over the old one trigger exactly this, which is why watching the **parent directory** is more robust than watching the file. - **Platform quirks.** On Windows, moving or renaming the watched directory produces no events, and deleting it reports `EPERM`. - **No security boundary.** The docs state the API gives no protection against malicious changes to the file system. ## Where notifications do not arrive The facility must exist underneath. The docs warn that watching can be unreliable, and sometimes impossible, on network file systems such as NFS and SMB and on host file systems shared into virtual machines or containers. There, **`fs.watchFile`** is the fallback: it polls with `stat`, every 5007 ms by default, which is slower and, per the docs, less reliable, and it watches one file per call. ## Designing a watcher that survives all of this 1. **Debounce.** Coalesce bursts of events for a short window before acting. 2. **Re-read state.** On any event, re-stat or re-scan the affected directory instead of trusting the event type and filename. 3. **Prune early.** Pass `ignore` for dependency and VCS directories, and watch only source roots. 4. **Watch directories, not files**, so atomic saves do not go silent. 5. **Offer polling** for network and container mounts, behind a flag. 6. **Manage the lifetime.** `persistent` defaults to `true`, so an open watcher keeps the process alive; close it with `watcher.close()` or an `AbortSignal`. The promise form, `fsPromises.watch`, yields events through an async iterator and drops overflow beyond `maxQueue` (2048 by default) with a warning. 7. **Listen for `'error'`.** An `FSWatcher` emits `'error'` when watching fails, and the docs say the errored watcher is no longer usable; recreate it rather than assuming it recovers. ## What it costs the process Native watching is cheap for Node itself: the fs reference notes that every callback and promise fs API uses libuv's threadpool **except** `fs.FSWatcher`, so idle watches occupy no thread. The costs sit elsewhere: kernel watch slots, the synchronous initial walk of the Linux emulation, and whatever rebuild work each event triggers. A dev tool that rebuilds on every raw event, without debouncing, is usually the real reason a watcher "pins a core".

  • A watcher that reloads config.json fires once and then never again on a Linux server. What is the likely cause?
    The file is replaced, not modified: a deploy tool or editor writes a new file and renames it over the old name. `fs.watch` on Linux watches the original inode, which is now gone, so the new file produces no events. Watch the containing directory and filter on the name, or re-create the watch after a `'rename'` event.
  • Why does a Node file watcher keep a short CLI from exiting, and how do you stop it?
    `persistent` defaults to `true`, so an active `FSWatcher` keeps the event loop alive. Call `watcher.close()`, pass an `AbortSignal` and abort it, or set `persistent: false` when the watch should not by itself hold the process open.

  • fs.watch behaves identically on Linux, macOS and Windows
  • The filename argument in the fs.watch callback is always provided
  • recursive: true on Linux is one cheap kernel watch on the root
  • Each fs.watch event corresponds to exactly one file save
  • fs.watchFile is the faster, preferred alternative to fs.watch

Assumes Node 24: recursive fs.watch on Linux dates from v19.1.0 and is emulated by Node; the ignore option was added in v24.14.0.