🎓 A1Learner
🔍
0 of 50 lessons completed

Watching Files

The fs module can watch a file for changes. Watching means Node tells the program when the file changes.

Watching one file

This watches watched.txt. The callback prints when the file changes.

const fs = require("fs");

const watcher = fs.watch("watched.txt", (eventType, filename) => {
  console.log("Changed: " + filename);
});

Watching a folder

This watches a whole folder. The callback names the file that changed.

const watcher = fs.watch("watchdir", (eventType, filename) => {
  console.log("Changed: " + filename);
});

Example

const fs = require("fs");

fs.writeFileSync("watched.txt", "First version");

const watcher = fs.watch("watched.txt", (eventType, filename) => {
  console.log("Changed: " + filename);
  watcher.close();
});

setTimeout(() => {
  fs.writeFileSync("watched.txt", "Second version");
}, 200);

setTimeout(() => {
  console.log("Done watching");
}, 1000);

Key points

  • fs.watch starts watching a file or folder.
  • fs.watch takes a callback with two inputs.
  • The first input names the kind of change.
  • The second input names the changed file.
  • The callback runs each time the watched file changes.
  • The first input is often the word change.
  • Call watcher.close when the watching is done.
  • A watcher keeps the program running until it is closed.

In this example, the program writes First version to watched.txt. The watcher starts and waits for a change. After a short wait, the program writes Second version to the same file. The watcher prints Changed with the file name and then closes. The last print shows Done watching.

Note

One change can fire the watcher more than once on some machines.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does fs.watch do?