Book Image

Node Cookbook - Fourth Edition

By : Bethany Griggs
4 (1)
Book Image

Node Cookbook - Fourth Edition

4 (1)
By: Bethany Griggs

Overview of this book

A key technology for building web applications and tooling, Node.js brings JavaScript to the server enabling full-stack development in a common language. This fourth edition of the Node Cookbook is updated with the latest Node.js features and the evolution of the Node.js framework ecosystems. This practical guide will help you to get started with creating, debugging, and deploying your Node.js applications and cover solutions to common problems, along with tips to avoid pitfalls. You'll become familiar with the Node.js development model by learning how to handle files and build simple web applications and then explore established and emerging Node.js web frameworks such as Express.js and Fastify. As you advance, you'll discover techniques for detecting problems in your applications, handling security concerns, and deploying your applications to the cloud. This recipe-based guide will help you to easily navigate through various core topics of server-side web application development with Node.js. By the end of this Node book, you'll be well-versed with core Node.js concepts and have gained the knowledge to start building performant and scalable Node.js applications.
Table of Contents (14 chapters)

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