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
- 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
- We need to also create a file that we can watch:
$ echo "Hello World!" > file.txt
- 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:
- To get started, import the required core Node.js modules:
const fs = require("fs");
- We also need the program to access a file we created:
const file = "./file.txt";
- Next, we call the
fs.watchFile()
function:fs.watchFile(file, (current, previous) => { return console.log(`${file} updated ${(current.mtime)}`); });
- Now, we can run the program in the Terminal with this:
$ node watch.js
- 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 runningwatch.js
:./file.txt updated Wed Mar 25 2020 00:38:31 GMT+0000 (Greenwich Mean Time)
- 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. - 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 apackage.json
file in your project directory. - 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 publicnpm
registry:$ npm install moment
If you open
package.json
, you will notice thatmoment
has been added under thedependencies
field. - We now need to import
moment
into ourwatch.js
file. Add the following, just below your file constant declaration:const moment = require("moment");
- 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}`);
- 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 totrue
, the numeric values returned from the object ofStats
would be specified asBigInt
.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