Getting File Details in Node.js
Learn how to retrieve file details using Node.js
Files contain various details that can be inspected using Node.js. One way to obtain these details is by using the stat()
method provided by the fs
module.
To use this method, simply pass the file path as a parameter. Once Node.js retrieves the file details, it will invoke the callback function you provide with two parameters: an error message (if applicable) and the file stats.
1 | const fs = require('fs'); |
Alternatively, Node.js also offers a synchronous version of the stat()
method. This version blocks the thread until the file stats are ready.
1 | const fs = require('fs'); |
The file information is stored in the stats
variable. What kind of information can we extract from the file stats?
We have access to various details, including:
- Checking whether the file is a directory or a regular file using
stats.isFile()
andstats.isDirectory()
. - Checking if the file is a symbolic link using
stats.isSymbolicLink()
. - Obtaining the file size in bytes using
stats.size
.
While there are additional advanced methods available, these basic methods will be sufficient for most day-to-day programming tasks.
1 | const fs = require('fs'); |
tags: [“Node.js”, “file details”, “fs module”, “stat()”, “file stats”]