Watching files and directories
The ability to receive when a file is added, removed, or updated can extremely useful. Node's fs
module supplies this functionality cross-platform; however, as we'll explore, the functionality across operating systems can be patchy.
In this recipe, we'll write a program that watches a file and outputs some data about the file when it changes. In the There's more... section, we'll explore the limitation of Node's watch functionality along with a third-party module that wraps the core functionality to make it more consistent.
Getting ready
Let's create a new folder called watching-files-and-directories
, create a package.json
in the folder, and then install the third-party human-time
module for nicely formatted time outputs:
$ mkdir watching-files-and-directories $ cd watching-files-and-directories $ npm init -y $ npm install --save human-time
We'll also create a file to watch:
$ echo "some content" > my-file.txt
Finally, we want to create a file called watcher...