filewatcher nodejs

// Step 1: Import the required modules
const fs = require('fs');
const path = require('path');

// Step 2: Define the path to the file you want to watch
const filePath = 'path/to/your/file.txt';

// Step 3: Create a function to handle file changes
const handleFileChange = (eventType, filename) => {
  if (filename) {
    console.log(`File ${filename} has been ${eventType}`);
  }
};

// Step 4: Create a FileWatcher instance
const fileWatcher = fs.watch(filePath, { persistent: true }, handleFileChange);

// Step 5: Listen for the 'close' event to handle the watcher's closure
fileWatcher.on('close', () => {
  console.log('File watcher closed.');
});

// Step 6: Handle process termination to close the file watcher
process.on('SIGINT', () => {
  fileWatcher.close();
  process.exit();
});