tezvyn:

fs.watch vs fs.watchFile

AI-drafted, machine-checkedSource: interviewintermediate
WHAT IT TESTS

file change detection mechanisms.

OUTLINE

watch uses OS event notifications, efficient but inconsistent across platforms, watchFile polls stat at an interval, reliable but slower.

RED FLAG

not knowing watch is event based versus polling.

WHAT THIS TESTS This examines depth of filesystem knowledge and awareness of the reliability versus efficiency tradeoff that underlies tools like dev-server watchers.

A GOOD ANSWER COVERS fs.watch relies on operating-system file change notifications: inotify on Linux, FSEvents on macOS, and ReadDirectoryChangesW on Windows. This makes it efficient because the OS pushes events rather than Node polling. The downside is inconsistency: behavior varies by platform, the filename argument is not always provided, a single change can fire multiple events, and events can be missed, especially over network filesystems. fs.watchFile takes the opposite approach: it polls the file by calling stat on a configurable interval and compares the previous and current stat objects, invoking the listener when they differ. Polling is portable and predictable but introduces detection latency equal to the interval and consumes CPU even when nothing changes. So watch favors performance, watchFile favors reliability and portability.

COMMON WRONG ANSWERS Saying both use OS events or both poll. Claiming watch is always strictly better, ignoring its dropped and duplicated events. Not knowing that watchFile latency is bounded by the poll interval.

LIKELY FOLLOW-UPS Why do production watchers like chokidar wrap fs.watch with extra logic. How would you debounce duplicate watch events. What problems appear on networked or mounted filesystems.

ONE CONCRETE EXAMPLE A hot-reload tool using fs.watch on macOS may receive two change events for one save because the editor writes a temp file then renames it, so naive code reloads twice. fs.watchFile with a 1-second interval would reliably report the change once but only up to a second after it happened, and would keep polling even on an idle file.

Read the original → nodejs.org

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.