Course contentsShow
← Node.js
Lesson 335 of 1,9804. I/O and File System OperationsFree lesson

Detecting File System Changes with Watchers

Implement event-driven file system monitoring to trigger automatic rebuilds or configuration reloads.

In this lesson, you will learn how to use Node.js file system watchers to trigger automated tasks, such as rebuilding your application or reloading configuration files, whenever a file changes on disk.

How File Watchers Work

Instead of constantly polling a file (repeatedly checking if it has changed), which wastes CPU cycles, Node.js leverages your operating system's native notification system (like inotify on Linux or FSEvents on macOS). By using the fs.watch method, you register a "listener" with the OS. The OS then signals Node.js only when a specific file or directory is modified, allowing your program to remain idle until an event actually occurs.

Implementing an Automatic Reload

Think of a scenario where you have a config.json file. You want your server to update its internal settings instantly whenever you save that file, without having to restart the entire process.

const fs = require('fs');

// Watch the configuration file for changes
fs.watch('config.json', (eventType, filename) => {
  if (filename && eventType === 'change') {
    console.log(`${filename} was modified. Reloading configuration...`);
    
    // Logic to re-read and apply the new config would go here
    const newConfig = fs.readFileSync('config.json', 'utf8');
    console.log('New configuration loaded!');
  }
});

In this code, the callback function acts as an event handler. When you save the file, the operating system triggers the event, the event loop captures it, and your logic executes immediately.

This is the foundation of "hot-reloading" in development tools. By binding your logic to these system-level events, you ensure your application stays perfectly in sync with the file system without the overhead of continuous polling. It is a powerful way to make your infrastructure "reactive," turning static files into dynamic inputs that drive your application's state.

Key Takeaway: File watchers utilize native OS event notifications to trigger code execution in response to disk changes, eliminating the need for inefficient polling while enabling live configuration reloading and automated build cycles.