fs.watch()

Watches for changes to a file or directory.

Since Node 0.x; async iterator Node 11.1 Spec ↗

Syntax

fs.watch(filename[, options][, listener])

Parameters

NameTypeRequiredDescription
filename string | Buffer | URL Yes The file or directory to watch.
options object | string No `recursive` (watch subdirectories), `persistent`, `encoding`, and `signal` to stop watching via an AbortController.
listener function No Callback `(eventType, filename)` where eventType is `'rename'` or `'change'`.

Returns

FSWatcher — An EventEmitter emitting change and error events.

Examples

import { watch } from 'node:fs';

const watcher = watch('./src', (event, file) => {
  console.log(event, file);
});
Output
change index.js
import { watch } from 'node:fs/promises';

const ac = new AbortController();
setTimeout(() => ac.abort(), 5000);
for await (const e of watch('.', { signal: ac.signal })) {
  console.log(e.eventType, e.filename);
}
Output
rename new.txt

Notes

Behavior is platform dependent: events may fire twice, `recursive` is unsupported on some Linux versions, and editors often emit a burst of events. Debounce the listener and use a library like chokidar for cross-platform reliability.

See also