Node file stats
How to get the details of a file using Node
Every file comes with a set of details that we can inspect using Node.
In particular, using the stat()
method provided by the fs
module.
You call it passing a file path, and once Node gets the file details it will call the callback function you pass, with 2 parameters: an error message, and the file stats:
const fs = require('fs')
fs.stat('/Users/flavio/test.txt', (err, stats) => {
if (err) {
console.error(err)
return
}
//we have access to the file stats in `stats`
})
Node provides also a sync method, which blocks the thread until the file stats are ready:
const fs = require('fs')
try {
const stats = fs.stat('/Users/flavio/test.txt')
} catch (err) {
console.error(err)
}
The file information is included in the stats variable. What kind of information can we extract using the stats?
A lot, including:
- if the file is a directory or a file, using
stats.isFile()
andstats.isDirectory()
- if the file is a symbolic link using
stats.isSymbolicLink()
- the file size in bytes using
stats.size
.
There are other advanced methods, but the bulk of what you’ll use in your day-to-day programming is this.
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 //= 1MB
})
→ I wrote 17 books to help you become a better developer:
- C Handbook
- Command Line Handbook
- CSS Handbook
- Express Handbook
- Git Cheat Sheet
- Go Handbook
- HTML Handbook
- JS Handbook
- Laravel Handbook
- Next.js Handbook
- Node.js Handbook
- PHP Handbook
- Python Handbook
- React Handbook
- SQL Handbook
- Svelte Handbook
- Swift Handbook
Also, JOIN MY CODING BOOTCAMP, an amazing cohort course that will be a huge step up in your coding career - covering React, Next.js - next edition February 2025