Categories
JavaScript Answers

How to watch a folder for changes using Node.js, and print file paths when they are changed?

Spread the love

To watch a folder for changes using Node.js, and print file paths when they are changed, we use the chokidar package.

For instance, we write

const chokidar = require("chokidar");

const watcher = chokidar.watch(path, { ignored: /^\./, persistent: true });

watcher
  .on("add", (path) => {
    console.log("File", path, "has been added");
  })
  .on("change", (path) => {
    console.log("File", path, "has been changed");
  })
  .on("unlink", (path) => {
    console.log("File", path, "has been removed");
  })
  .on("error", (error) => {
    console.error("Error happened", error);
  });

to create a watcher with watch to watch a file or directory at the path for changes.

Then we call on to watch for additions by calling on with 'add'.

We watch for changes by calling on with 'change'.

And we watch for deletions by calling on with 'unlink'.

And we watch for any errors by calling on with 'error'.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *