To get the size of a file in Node.js, you can use the stat()
method provided by the built-in fs
module. This method works asynchronously and lists the statistics of a file at the given path.
All you need to do is pass in the file path and a callback function to the fs.stat()
method. Once the file statistics are populated by Node.js, it will invoke the callback function with two arguments: an error message and the file stats:
const fs = require('fs')
// Read file stats
fs.stat('file.txt', (err, stats) => {
if (err) {
console.log(`File doesn't exist.`)
} else {
console.log(stats)
}
})
The stats
object returned by the fs.stat()
function looks like the following:
Stats {
dev: 16777221,
mode: 33279,
nlink: 1,
uid: 501,
gid: 20,
rdev: 0,
blksize: 4096,
ino: 5172976,
size: 290,
blocks: 8,
atimeMs: 1606143471354.2327,
mtimeMs: 1599218860000,
ctimeMs: 1606074010041.4927,
birthtimeMs: 1605423684000,
atime: 2020-11-23T14:57:51.354Z,
mtime: 2020-09-04T11:27:40.000Z,
ctime: 2020-11-22T19:40:10.041Z,
birthtime: 2020-11-15T07:01:24.000Z
}
To get the size of the file, you can use the size
property in the stats
object:
const size = stats.size; // 290 bytes
The size of the file is returned in bytes. You can convert it into a human-readable format to display publicly.
The fs
module also provides a synchronous variant of stat()
called statSync()
that blocks the execution of the Node.js event loop until the file statistics are ready:
try {
const stats = fs.statSync('file.txt')
} catch (err) {
console.log(err)
}
The fs.stat()
method can also be used to check if the path is a file, a directory, or a symbolic link, as shown below:
const fs = require('fs')
// Read file stats
fs.stat('file.txt', (err, stats) => {
if (err) {
console.log(`File doesn't exist.`)
return
}
console.log(stats.isFile()) // true
console.log(stats.isDirectory()) // false
console.log(stats.isSymbolicLink()) // false
})
✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.