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.

JavascriptCli Tooling

Code

javascriptsnippet
19 lines
// 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 closed

How 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/promises comes 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

FAQ

Do I need to install anything before running this?
Nothing needs installing: `node:fs/promises` ships with Node.js itself.