fs.watch Emits File Change Events
fs.watch streams change and rename events for a directory; debounce writes deliberately and always close the watcher so the process can exit.
Code
// fs.watch turns directory changes into events; close the watcher to stop.
import { mkdir, writeFile, rm } from 'node:fs/promises';
import { watch } from 'node:fs';
const dir = 'watched';
await mkdir(dir, { recursive: true });
const watcher = watch(dir, (event, filename) => {
console.log('event:', event, '| file:', filename);
});
await writeFile(`${dir}/notes.txt`, 'first');
await new Promise((resolve) => setTimeout(resolve, 150));
await writeFile(`${dir}/notes.txt`, 'second');
await new Promise((resolve) => setTimeout(resolve, 150));
watcher.close();
await rm(dir, { recursive: true, force: true });
console.log('watcher closed');Output
Captured from a sandboxed run of this snippet in the build pipeline.
event: rename | file: notes.txt
event: change | file: notes.txt
event: change | file: notes.txt
event: change | file: notes.txt
watcher closedHow it works
Await points sequence the asynchronous work; a rejection lands at the awaiting line. node:fs/promises, node:fs supplies mkdir, writeFile, rm, watch — built-in surface, no package involved.
Top-level bindings dir, watcher hold the demo state — nothing sits inside a function scope.
Points of care
- No install needed:
node:fs/promisescomes with Node.js itself.
Applying it
Output lines are prefixed (event:, watcher closed), making each step’s effect easy to spot.
Statements that matter
await new Promise((resolve) => setTimeout(resolve, 150));
const watcher = watch(dir, (event, filename) => {
console.log('event:', event, '| file:', filename);
});
await rm(dir, { recursive: true, force: true });
Interactive Tools for This Topic
DOM Event Propagation VisualizerVisualize DOM event capturing, targeting, and bubbling phases in real time. Toggle stopPropagation and stopImmediatePropagation to see how events traverse the tree.Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
FAQ
- Do I need to install anything before running this?
- Nothing needs installing: `node:fs/promises` ships with Node.js itself.
Report a problem with this exampleOpens a pre-filled issue on GitHub.