Watching for file changes
As we are already familiar with the Node.js filesystem library, let’s build a simple script that watches for file changes. We will use the fs.watch method to watch for file changes. This method receives two arguments, the path to the file to watch and a callback function that will be called when the file changes. The callback function receives two arguments, the event type and the filename. The event type can be rename or change. The rename event is triggered when the file is renamed or deleted. The change event is triggered when the file is modified.
Now, we will create a simple program to detect file changes:
- Let’s create a file called
watch.mjsand add the following code:import { watch } from 'node:fs'; console.log('Watching for file changes...'); watch('./watch.txt', (eventType, filename) => { console.log('-----------------------------'); ...