-
Book Overview & Buying
-
Table Of Contents
-
Feedback & Rating

Node Cookbook
By :

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.
file-watching
:$ mkdir file-watching $ cd file-watching
$ echo "Hello World!" > file.txt
watch.js
file:$ touch watch.js
Now that we have created our directory and file, we can move on to the recipe.
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:
const fs = require("fs");
const file = "./file.txt";
fs.watchFile()
function:fs.watchFile(file, (current, previous) => { return console.log(`${file} updated ${(current.mtime)}`); });
$ node watch.js
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)
moment.js
module. It is an external module that enables you to manipulate dates and times in JavaScript. $ 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.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.
moment
into our watch.js
file. Add the following, just below your file constant declaration:const moment = require("moment");
moment.js
:const time = moment().format("MMMM Do YYYY, h:mm:ss a"); return console.log(`${filename} updated ${time}`);
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
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:
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.true
.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:
true
. false
. The recursive option is only supported on macOS and Windows operating systems.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/.
Change the font size
Change margin width
Change background colour