0
0
Node.jsframework~5 mins

Watching files for changes in Node.js

Choose your learning style9 modes available
Introduction

Watching files lets your program notice when a file changes. This helps you update things automatically without restarting.

You want to reload a web server when code files change.
You want to rebuild assets like CSS or JavaScript when source files update.
You want to run tests automatically after saving code.
You want to monitor log files and react when new entries appear.
Syntax
Node.js
const fs = require('fs');

fs.watch('filename.txt', (eventType, filename) => {
  if (filename) {
    console.log(`${filename} file Changed: ${eventType}`);
  }
});

fs.watch watches a file or directory for changes.

The callback runs when a change happens, giving the event type and filename.

Examples
Watch a single file and log the event type and filename when it changes.
Node.js
fs.watch('notes.txt', (eventType, filename) => {
  console.log(`Event: ${eventType} on ${filename}`);
});
Watch the current folder for any file changes and log them.
Node.js
fs.watch('.', (eventType, filename) => {
  if (filename) {
    console.log(`File ${filename} in current folder changed: ${eventType}`);
  }
});
Create a watcher object and listen for 'change' events.
Node.js
const watcher = fs.watch('data.txt');
watcher.on('change', (eventType, filename) => {
  console.log(`Change detected on ${filename}. Event type: ${eventType}`);
});
Sample Program

This program watches the file test.txt. When you change and save that file, it prints a message showing the file name and what kind of change happened.

Node.js
const fs = require('fs');

console.log('Start watching test.txt for changes...');

fs.watch('test.txt', (eventType, filename) => {
  if (filename) {
    console.log(`File ${filename} changed. Event type: ${eventType}`);
  } else {
    console.log('Filename not provided');
  }
});
OutputSuccess
Important Notes

Sometimes the filename may be missing depending on the system. Always check before using it.

fs.watch is good for simple watching but may miss some events on some platforms. For more reliable watching, consider libraries like chokidar.

Watching many files can use system resources, so watch only what you need.

Summary

Watching files helps your program react to changes automatically.

Use fs.watch to watch files or folders in Node.js.

Always check if the filename is provided in the callback.