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.
const fs = require('fs');
fs.stat('/Users/flavio/test.txt', (err, stats) => {
if (err) {
console.error(err);
return;
}
// Access the file stats within the `stats` object
});
Alternatively, Node.js also offers a synchronous version of the stat()
method. This version blocks the thread until the file stats are ready.
const fs = require('fs');
try {
const stats = fs.statSync('/Users/flavio/test.txt');
} catch (err) {
console.error(err);
}
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.
const fs = require('fs');
fs.stat('/Users/flavio/test.txt', (err, stats) => {
if (err) {
console.error(err);
return;
}
stats.isFile(); // true
stats.isDirectory(); // false
stats.isSymbolicLink(); // false
stats.size; // 1024000 (equals 1MB)
});