Watching files lets your program notice when a file changes. This helps you update things automatically without restarting.
Watching files for changes in 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.
fs.watch('notes.txt', (eventType, filename) => { console.log(`Event: ${eventType} on ${filename}`); });
fs.watch('.', (eventType, filename) => { if (filename) { console.log(`File ${filename} in current folder changed: ${eventType}`); } });
const watcher = fs.watch('data.txt'); watcher.on('change', (eventType, filename) => { console.log(`Change detected on ${filename}. Event type: ${eventType}`); });
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.
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'); } });
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.
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.