Inspecting file metadata
The fs
module generally provides APIs that are modeled around Portable Operating System Interface (POSIX) functions. The fs
module includes APIs that facilitate the reading of directories and file metadata.
In this recipe, we will create a small program that returns information about a file, using functions provided by the fs
module.
Getting ready
Get started by creating a directory to work in:
$ mkdir fetching-metadata $ cd fetching-metadata
We'll also need to create a file to read and a file for our program:
$ touch metadata.js $ touch file.txt
How to do it
Using the files created, we will create a program that gives information about the file we pass to it as a parameter:
- As in the previous handling I/O recipes, we first need to import the necessary core modules. For this recipe, we just need to import the
fs
module:const fs = require("fs");
- Next, we need the program to be able to read the filename as a command-line argument. To read the file argument, we can use
process.argv[2]
. Add the following line to your program:const file = process.argv[2];
- Now, we will create our
printMetadata()
function:function printMetadata(file) { const fileStats = fs.statSync(file); console.log(fileStats); }
- Add a call to the
printMetadata()
function:printMetadata(file);
- You can now run the program, passing it the
./file.txt
parameter. Run your program with the following:$ node metadata.js ./file.txt
- Expect to see output similar to the following:
Stats { dev: 16777224, mode: 33188, nlink: 1, uid: 501, gid: 20, rdev: 0, blksize: 4096, ino: 3684101, size: 0, blocks: 0, atimeMs: 1585337526680.254, mtimeMs: 1585337526680.254, ctimeMs: 1585337722432.1917, birthtimeMs: 1585337526680.254, atime: 2020-03-27T19:32:06.680Z, mtime: 2020-03-27T19:32:06.680Z, ctime: 2020-03-27T19:35:22.432Z, birthtime: 2020-03-27T19:32:06.680Z }
- You can try adding some random text to
file.txt
and rerun your program; observe that thesize
andmtime
values have been updated. - Now let's see what happens when we pass a non-existent file to the program:
$ node metadata.js ./not-a-file.txt internal/fs/utils.js:230 throw err; ^ Error: ENOENT: no such file or directory, stat 'nofile'
The program throws an exception.
- We should catch this exception and output a message to the user saying the file path provided does not exist. To do this, change the
printMetadata()
function to this:function printMetadata(file) { try { const fileStats = fs.statSync(file); console.log(fileStats); } catch (err) { console.error("Error reading file path:", file); } }
- Run the program again with a non-existent file; this time you should see that the program handled the error rather than throwing an exception:
$ node metadata.js ./not-a-file.txt Error reading file: undefined
How it works
process.argv
is a property on the global process object that returns an array containing the arguments that were passed to the Node.js process. The first element of the process.argv
array, process.argv[0]
is the path of the node
binary that is running. The second element is the path of the file we're executing, in this case, meta.js
. In the recipe, we passed the filename as the third command-line argument and therefore referenced it with process.argv[2]
.
Next, we created a printMetadata()
function that called statSync(file)
. statSync()
is a synchronous function that returns information about the file path that is passed to it. The file path passed can be either a file or a directory. The information returned is in the form of a stats
object. The following table lists the information returned on the stats
object:
Important note
In this recipe, we used only the synchronous File System APIs. For most of the fs
APIs, there are both synchronous and asynchronous versions of each function. Refer to the Working with files asynchronously section of the previous recipe for more information about using asynchronous File System APIs.
In the final steps of this recipe, we edited our printMetadata()
function to account for invalid file paths. We did this by wrapping the statSync()
function in a try/catch
statement.
There's more
Next, we'll look at how we can check file access and modify file permissions and how to examine a symbolic link (symlink).
Checking file access
It is recommended that if you're attempting to read, write, or edit a file, you follow the approach of handling the error if the file is not found, as we did in the recipe.
However, if you simply wanted to check the existence of a file, you could use the fs.access()
or fs.accessSync()
APIs. Specifically, the fs.access()
function tests the user's permissions for accessing the file or directory passed to it. The function also allows an optional argument of mode to be passed to it, where you can request the function to do a specific access check using the Node.js File Access Constants. This list of Node.js File Access Constants is available in the Node.js fs
module API documentation: https://nodejs.org/api/fs.html#fs_file_access_constants. These enable you to check whether the Node.js process can read, write, or execute the file path provided.
Important note
There is a legacy API that is now deprecated called fs.exists()
. It is not recommended you use this function—the fs.access()
APIs should be used instead.
Modifying file permissions
The Node.js fs
module provides APIs that can be used to alter the permissions on a given file. As with many of the other fs
functions, there is both an asynchronous API, chmod()
, and an equivalent synchronous API, chmodSync()
. Both functions take a file path and mode
as the first and second arguments, respectively. The asynchronous function accepts a third parameter, which is the callback function to be executed upon completion.
Important note
chmod
is a command that is used to change access permissions of file system objects on Unix and similar operating systems. If you're unfamiliar with Unix file permissions, it is recommended you refer to the Unix manual pages (https://linux.die.net/man/1/chmod).
The mode argument can be either in the form of a numeric bitmask using a series of constants provided by the fs
module or a sequence of three octal digits. The constants that can be used to create the bitmask to define user permissions are defined in the Node.js API documentation: https://nodejs.org/api/fs.html#fs_file_modes.
Imagine that you have a file that currently has the following permissions:
- Owner readable and writeable
- Group readable
- Readable only by all other users (sometimes referred to as world readable)
If we wanted to additionally grant write access to those in the same group in our shell, we could use the following Node.js code:
const fs = require("fs"); const file = "./file.txt"; fs.chmodSync( file, fs.constants.S_IRUSR | fs.constants.S_IWUSR | fs.constants.S_IRGRP | fs.constants.S_IWGRP | fs.constants.S_IROTH );
As you can see, this code is quite verbose. Adding a complex series of permissions would require passing a numerous amount of constants to create the numeric bitmask. Alternatively, we can pass the chmodSync()
function the octal representation of file permissions, similar to how you can when using the Unix chmod
command. We're going to change the permissions using the equivalent of chmod 664
from the command line, but via Node.js:
const fs = require("fs"); const file = "./file.txt"; fs.chmodSync(file, 0o664);
Important Note
Refer to https://mason.gmu.edu/~montecin/UNIXpermiss.htm for more detailed information on how Unix permissions work.Windows File Permissions: The Windows operating system does not have as refined file permissions as on Unix—it is only possible to denote a file as writeable or non-writeable.
Inspecting symbolic links
A symbolic link, or symlink, is a special file that stores a reference to another file or directory. When the stat
or statSync()
function from the Inspecting file metadata recipe is run on a symbolic link, it will return information about the file the symbolic link references, rather than the symbolic link itself.
The Node.js fs
module does, however, provide the functions named lstat()
and lstatSync()
that inspect the symbolic link itself:
- To create a symbolic link, you can use the following command:
$ ln -s file.txt link-to-file
- Now, you can use the Node.js REPL (Read-Eval-Print Loop) to test the
lstatSync()
function. The Node.js REPL is an interactive shell we can pass statements to, and it will evaluate them and return the result to the user. - To enter the Node.js REPL, type
node
in your shell:$ node Welcome to Node.js v14.0.0. Type ".help" for more information. >
- You can then type commands such as the following:
> console.log("Hello World!"); Hello World! Undefined
- Now you can try out the
lstatSync
command:> fs.lstatSync("link-to-file"); Stats { dev: 16777224, mode: 41453, nlink: 1, ... }
Note that we did not need to explicitly import the Node.js fs
module. The REPL automatically loads the core (built-in) Node.js modules so that they are available to be used. The REPL is a useful tool for testing out commands without having to create new files.
See also
- The Handling standard I/O recipe in this chapter