Node file stats
By Flavio
Published · Updated
Tagged: Node.js
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.
Using stat() with async/await
In new code I use the promise version from node:fs/promises. It returns the same fs.Stats object:
import { stat } from 'node:fs/promises'
try {
const stats = await stat('/Users/flavio/test.txt')
console.log(stats.size)
} catch (error) {
console.error(error)
}
Top-level await works in ES modules (.mjs files, or "type": "module" in package.json). In CommonJS, put the code inside an async function. I wrote more about this in how to use the Node.js fs module with async/await.
The most useful properties and methods
Here are some of the most useful properties and methods:
stats.isFile()returnstruefor a regular filestats.isDirectory()returnstruefor a directorystats.isSymbolicLink()returnstruefor a symbolic link (only withlstat(), see below)stats.sizecontains the size in bytesstats.mtimecontains the last modification time, as aDatestats.mtimeMscontains the same time as a number of millisecondsstats.modecontains the file type and permission bits
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)
})
There are also isFIFO(), isSocket(), isBlockDevice() and isCharacterDevice() for the special file types you find on Unix systems.
mtime, ctime, atime and birthtime
A Stats object has 4 timestamps, and the names are easy to mix up:
mtime: when the file content was last modifiedctime: when the file status changed, for example its permissions or owner. It also changes when the content changesatime: when the file data was last accessedbirthtime: when the file was created
ctime is not the creation time. I checked it with a chmod: the permissions change updates ctime but leaves mtime alone.
import { stat, chmod } from 'node:fs/promises'
const before = await stat('test.txt')
await chmod('test.txt', 0o600)
const after = await stat('test.txt')
console.log(after.mtimeMs === before.mtimeMs) // true
console.log(after.ctimeMs > before.ctimeMs) // true
To show “last modified” in an app, use mtime. Be careful with birthtime: not every file system stores a creation time, so don’t build logic that depends on it.
Each timestamp has a Date version (mtime) and a number version (mtimeMs). The number is handy to compare or sort:
files.sort((a, b) => b.stats.mtimeMs - a.stats.mtimeMs) // newest first
Showing the file size in KB or MB
size is always in bytes. Convert it yourself:
function formatSize(bytes) {
if (bytes < 1024) return `${bytes} B`
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`
return `${(bytes / 1024 / 1024).toFixed(1)} MB`
}
const stats = await stat('video.mp4')
console.log(formatSize(stats.size))
For a directory, size is not the total size of the files inside it. You have to walk the folder and add up the size of each file.
Reading the file permissions
mode mixes the file type and the permission bits. Mask it with 0o777 to keep only the permissions, then print it in octal:
const stats = await stat('test.txt')
console.log((stats.mode & 0o777).toString(8)) // e.g. 644
stat() vs lstat() with symbolic links
stat() follows symbolic links. Use lstat() instead when you need to check the link itself with stats.isSymbolicLink().
import { stat, lstat } from 'node:fs/promises'
// link.txt is a symlink to test.txt
console.log((await stat('link.txt')).isSymbolicLink()) // false
console.log((await lstat('link.txt')).isSymbolicLink()) // true
The same applies to a link that points to a folder: stat() says isDirectory() is true, while lstat() says false, because the link itself is not a directory.
When the file does not exist
If the path does not exist, stat() fails with an error whose code is 'ENOENT'. Check the code so you don’t hide other errors, like a permission problem:
try {
const stats = await stat('missing.txt')
} catch (error) {
if (error.code === 'ENOENT') {
console.log('No such file')
} else {
throw error
}
}
Should you use stat() to check if a file exists?
Not if you are going to open, read or write the file right after. The Node docs say this is not recommended. Between your check and the read, another process can delete or create the file. Read the file directly and handle the ENOENT error instead:
import { readFile } from 'node:fs/promises'
try {
const content = await readFile('config.json', 'utf8')
} catch (error) {
if (error.code !== 'ENOENT') throw error
// use the default config
}
If you only want to know whether something exists, without using it, fs.existsSync() returns true or false. The callback version fs.exists() is deprecated, but fs.existsSync() is not.
The sync version
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)
}
Pass throwIfNoEntry: false to get undefined instead of an exception when the file is missing:
const stats = fs.statSync('maybe.txt', { throwIfNoEntry: false })
if (stats) {
console.log(stats.size)
}
Use the asynchronous version in server code when you do not want file access to block other work. The sync version is fine in a CLI script or at startup.
Checking many files in a folder
When you list a folder and only need to know which entries are files and which are folders, you don’t need to call stat() on each one. readdir() with withFileTypes: true gives you objects with the same isFile(), isDirectory() and isSymbolicLink() methods:
import { readdir } from 'node:fs/promises'
const entries = await readdir('.', { withFileTypes: true })
for (const entry of entries) {
console.log(entry.name, entry.isDirectory())
}
Call stat() only when you also need the size or the dates.
Want me to talk about your product? You can sponsor this site.
Related posts about node: