HomeTutorsContact

How to track folder or file changes in Node.js?

By Gulshan Saini
Published in NodeJS
August 02, 2020
1 min read

Node.js comes with builtin method fs.watch() method that will emit ‘change’ event whenver specific directory or file is modified

Example

fs.watch(
  './folder/or/file/path/to/watch',
  { encoding: 'buffer' },
  (eventType, filename) => {
    if (filename) {
      console.log(filename)
      // Prints: <Buffer ...>
    }
  }
)

Save above code in watch.js file and run the program node watch.js. Make sure you change folder or file name.

Once you run the program, it will continuosly watch for any changes in specific folder or file and prints buffer once the changes are found.

Let’s test our code

Make some changes in folder or file being watched and check the console. You should see buffer on your terminal as shown below - contents of buffer may differ

<Buffer 66 69 6c 65 2e 6a 73>

Tags

#nodejs
Previous Article
What Is HTML 5 Doctype?

Related Posts

NodeJS
What is the max HTTP header size in NodeJS server?
August 17, 2020
1 min
Gulshan Saini

Gulshan Saini

Fullstack Developer

Topics

Angular
JavaScript
ReactJS
Typescript

Subscribe to our newsletter!

We'll send you the best of our blog just once a month. We promise.
© 2021, All Rights Reserved.

Quick Links

Contact UsBrowserCSSPythonPuppeteer

Social Media