First you’ll need to start a new node server. Once it’s done, lets see how to read file size on a node server, and we’ll see how to format the size to be readable by human !
For this we’ll use the package fs
provided by nodejs and the stat()
function.
You can also use the
statSync()
function which is a synchronous variant that blocks the execution of nodejs event loop until it returns the stat of the file.
const fs = require('fs') // Read file stats fs.stat('movie.mp4', (err, stats) => { if (err) { console.log(`File doesn't exist.`) } else { console.log('Stats', stats) } })
It will log a response that will look like this :
Stats { dev: 16777220, mode: 16877, nlink: 3, uid: 501, gid: 20, rdev: 0, blksize: 4096, ino: 14214262, size: 96000, blocks: 0, atimeMs: 1561174653071.963, mtimeMs: 1561174614583.3518, ctimeMs: 1561174626623.5366, birthtimeMs: 1561174126937.2893, atime: 2019-06-22T03:37:33.072Z, mtime: 2019-06-22T03:36:54.583Z, ctime: 2019-06-22T03:37:06.624Z, birthtime: 2019-06-22T03:28:46.937Z }
to get only the size you simply need to call :
const size = stat.size console.log(size) //96000 bytes
Now bytes are not a great way to refer to file size from a human perspective. To make this more human readable we can use this function :
const humanFileSize => (bytes, si=false, dp=1) { const thresh = si ? 1000 : 1024; if (Math.abs(bytes) < thresh) { return bytes + ' B'; } const units = si ? ['kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'] : ['KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB']; let u = -1; const r = 10**dp; do { bytes /= thresh; ++u; } while (Math.round(Math.abs(bytes) * r) / r >= thresh && u < units.length - 1); return bytes.toFixed(dp) + ' ' + units[u]; } console.log(humanFileSize(1551859712)) // 1.4 GiB console.log(humanFileSize(5000, true)) // 5.0 kB console.log(humanFileSize(5000, false)) // 4.9 KiB console.log(humanFileSize(999949, true)) // 999.9 kB console.log(humanFileSize(999950, true)) // 1.0 MB console.log(humanFileSize(999950, true, 2)) // 999.95 kB console.log(humanFileSize(999500, true, 0)) // 1 MB
First value you can input is the size in bytes, secondly you can specify if you want it in binary or decimal convention and lastly how many number you want after the comma.
With this function you can log file size understandable by a user. Bytes is the reference value for file size but is complicated to understand directly by humans as number can grow quickly. That’s why it’s better to log it in different size that are understandable by humans.