Categories
JavaScript Answers

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

Spread the love

Sometimes, we want to watch a folder for changes and print file paths when they are changed with Node.js.

In this article, we’ll look at how to watch a folder for changes and print file paths when they are changed with Node.js.

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

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

To install it, we run

npm i chokidar

then we use it by writing

const chokidar = require('chokidar');

const watcher = chokidar.watch('file or dir', {
  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 that watches for 'file or dir' changes.

And then we call watcher.on with various event names and their event handlers.

The 'change' event is triggered when files are changed in the folders being watched.

Conclusion

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

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 *