Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Node Cookbook

You're reading from   Node Cookbook Discover solutions, techniques, and best practices for server-side web development with Node.js 14

Arrow left icon
Product type Paperback
Published in Nov 2020
Publisher Packt
ISBN-13 9781838558758
Length 512 pages
Edition 4th Edition
Languages
Tools
Arrow right icon
Author (1):
Arrow left icon
Bethany Griggs Bethany Griggs
Author Profile Icon Bethany Griggs
Bethany Griggs
Arrow right icon
View More author details
Toc

Table of Contents (14) Chapters Close

Preface 1. Chapter 1: Introducing Node.js 14 2. Chapter 2: Handling I/O FREE CHAPTER 3. Chapter 3: Streams, Streams, Streams 4. Chapter 4: Using Web Protocols 5. Chapter 5: Developing Node.js modules 6. Chapter 6: Exploring Node.js web Frameworks 7. Chapter 7: Working with Databases 8. Chapter 8: Testing with Node.js 9. Chapter 9: Securing Node.js Applications 10. Chapter 10: Performance Optimization 11. Chapter 11: Deploying Node.js Microservices 12. Chapter 12: Debugging Node.js 13. Other Books You May Enjoy

Watching for file updates

Node.js's fs module provides functionality that enables you to watch files and track when files or directories are created, updated, or deleted.

In this recipe, we'll create a small program named watch.js that watches for changes in a file using the watchFile() API and then prints a message when a change has occurred.

Getting ready

  1. For this recipe, we'll want to work inside a new directory. Create and change into a directory called file-watching:
    $ mkdir file-watching
    $ cd file-watching
  2. We need to also create a file that we can watch:
    $ echo "Hello World!" > file.txt 	
  3. Create the watch.js file:
    $ touch watch.js

Now that we have created our directory and file, we can move on to the recipe.

How to do it

We're going to create a program that watches for changes in a file. We will be using the fs module and, specifically, the watchFile() method to achieve this:

  1. To get started, import the required core Node.js modules:
    const fs = require("fs");
  2. We also need the program to access a file we created:
    const file = "./file.txt";
  3. Next, we call the fs.watchFile() function:
    fs.watchFile(file, (current, previous) => {  
        return console.log(`${file} updated ${(current.mtime)}`);
    });
  4. Now, we can run the program in the Terminal with this: 
    $ node watch.js 
  5. In your editor, open file.txt and make some edits, saving between each one. You will notice that each time you save, a log entry appears in the Terminal where you're running watch.js:
    ./file.txt updated Wed Mar 25 2020 00:38:31 GMT+0000 (Greenwich Mean Time)
  6. While we're here, we can make the timestamp more readable. To do this, we're going to use the moment.js module. It is an external module that enables you to manipulate dates and times in JavaScript.
  7. First, we need to initialize a new project. Do this by typing $ npm init --yes. Chapter 5, Developing Node.js Modules will go into more detail about this command. For now, we'll pass the --yes option to accept the defaults. You should now have a package.json file in your project directory.
  8. Now we can install the moment.js module. Note that this step will require an internet connection, as the package will be downloaded from the public npm registry:
    $ npm install moment 

    If you open package.json, you will notice that moment has been added under the dependencies field.

  9. We now need to import moment into our watch.js file. Add the following, just below your file constant declaration:
    const moment = require("moment");
  10. Add and change the following lines to format the date using moment.js:
      const time = moment().format("MMMM Do YYYY, h:mm:ss a");
      return console.log(`${filename} updated ${time}`);
  11. Rerun the program and make further edits to file.txt—observe that the time is now in a more readable format:
    $ node watch.js
    ./file.txt updated March 27th 2020, 3:38:27 pm

How it works

In the recipe, we used the watchFile() function to watch for changes on a given file path. The function accepts three arguments—a filename, a list of options, and a listener function. The options object can include the following:

  • BigInt: This defaults to false; when set to true, the numeric values returned from the object of Stats would be specified as BigInt. BigInt is a JavaScript object that allows you to represent larger numbers more reliably.
  • Persistent: This value indicates whether the Node.js process should continue to run while files are still being watched. It defaults to true.
  • Interval: The interval value controls how often the file should be polled for changes, measured in milliseconds. The default value is 5,007 milliseconds when no interval is supplied.

The listener function supplied to the watchFile() function will execute every time a change is detected. The listener function's arguments current and previous are both Stats objects, representing the current and previous state of the file.

Our listener function passed to watchFile() is executed each time a change has been detected in the file being watched. Every time the file is updated, our listener function logs the message to STDOUT.

The Node.js fs module provides another function watch that watches for changes in files but can also watch for directories. This function differs from watchFile() as it utilizes the operating system's underlying file system notification implementation, rather than polling for changes.

Although faster and more reliable than the watchFile() API, the Watch API is not consistent across various platforms. This is because the Watch API is dependent on the underlying operating systems method of notifying file system changes. The Node.js API documentation goes into more detail about the limitations of the Watch API across different platforms: https://nodejs.org/docs/latest/api/fs.html#fs_availability.

The watchFile() function accepts three parameters—the file path, an array of options, and a listener function. The options that can be passed via the options parameter are as follows:

  • Persistent: The persistent option is a Boolean that indicates whether the Node.js process should continue to run while files are still being watched. By default, the persistent option is set to true.
  • Recursive: The recursive option is another Boolean that allows the user to specify whether changes in subdirectories should be watched – by default, this value is set to false. The recursive option is only supported on macOS and Windows operating systems.
  • Encoding: The encoding option is used to specify which character encoding should be used for the filename specified—the default is utf8.

The listener function that is passed to the watch() API is slightly different to the listener function passed to the watchFile() API. The arguments to the listener function are eventType and trigger, where eventType is either change or rename and trigger is the file that triggered an event. The following code represents a similar task to what we implemented in our recipe but using the Watch API:

const fs = require("fs");
const file = "./file.txt";
const moment = require("moment");
fs.watch(file, (eventType, filename) => {
    const time = moment().format("MMMM Do YYYY, h:mm:ss a");
    return console.log(`${filename} updated ${time}`);
});

The final steps of the recipe cover installing, importing, and using the npm module, moment.js. moment.js is a popular JavaScript library that enables users to parse, validate, and display dates and times. In the recipe, we used the module to format the last updated time in a more readable date and time format, MMMM DD YYYY, h:mm:ss a. It is possible to customize how you want moment.js to display the date format, as in this example:

moment().format('dddd'); // Saturday
moment().format("MMM Do YY"); // Mar 28th 20
moment().format(); // 2020-03-28T16:59:14+00:00

Refer to the Moment.js documentation for the list of available formats and APIs: https://momentjs.com/docs/.

See also

  • The Consuming Node.js modules recipe in Chapter 5, Developing Node.js Modules
You have been reading a chapter from
Node Cookbook - Fourth Edition
Published in: Nov 2020
Publisher: Packt
ISBN-13: 9781838558758
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image