Node file stats
By Flavio Copes
Learn how to inspect files in Node.js with stat(), including file type, size, and modification time, and when to use lstat() for symbolic links.
Every file comes with details that we can inspect using Node.
Use the stat() method provided by the fs module. Pass it a path and a callback:
const fs = require('node:fs')
fs.stat('/Users/flavio/test.txt', (error, stats) => {
if (error) {
console.error(error)
return
}
console.log(stats.size)
})
The callback receives an fs.Stats object.
Here are some of the most useful properties and methods:
stats.isFile()returnstruefor a regular filestats.isDirectory()returnstruefor a directorystats.sizecontains the size in bytesstats.mtimecontains the last modification time
Example:
const fs = require('node:fs')
fs.stat('/Users/flavio/test.txt', (error, stats) => {
if (error) {
console.error(error)
return
}
console.log(stats.isFile())
console.log(stats.isDirectory())
console.log(stats.size)
})
stat() follows symbolic links. Use lstat() instead when you need to check the link itself with stats.isSymbolicLink().
Node also provides statSync(), which blocks until the file details are ready:
const fs = require('node:fs')
try {
const stats = fs.statSync('/Users/flavio/test.txt')
console.log(stats.size)
} catch (error) {
console.error(error)
}
Use the asynchronous version in server code when you do not want file access to block other work.
Want me to talk about your product? You can sponsor this site.
Related posts about node: