Automatically format size string in Node.js
Problem:
In NodeJS, you got a size of a file in bytes, but you want to format it for better readability.
For example, if your size is 10000
bytes, you want to print 10 kilobytes
, but if it is 1200000
, you want to print 1.20 Megabytes
.
Solution
Use this function:
function autoFormatFilesize(fileSize) {
if (fileSize > 1000000000) {
return (fileSize / 1000000000.0)
.toPrecision(3) + " gigabytes";
} else if (fileSize > 1000000) {
return (fileSize / 1000000.0)
.toPrecision(3) + " megabytes";
} else if (fileSize > 1000) {
return (fileSize / 1000.0)
.toPrecision(3) + " kilobytes";
} else {
return fileSize + " bytes"
}
}
This code always outputs three digits. Depending on the sizess you’re handling, you might need to add terabytes or even petabytes to the list or you might need to change the precision of the output.
If you’re looking for an off-the-shelf library with more features, take a look at bytes.js which you can use like this:
const bytes = require('bytes');
console.log(bytes(1024)); //Prints "1 kB"