file-size-pretty
Version:
Convert file sizes like 34892823 into human-readable formats like 33.2 MB.
16 lines (13 loc) • 530 B
JavaScript
// index.js
function fileSizePretty(bytes, decimals = 1, options = {}) {
if (bytes === 0) return '0 B';
const { standard = 'binary' } = options;
const k = standard === 'si' ? 1000 : 1024;
const sizes = standard === 'si'
? ['B', 'kB', 'MB', 'GB', 'TB', 'PB']
: ['B', 'KB', 'MB', 'GB', 'TB', 'PB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
const size = parseFloat((bytes / Math.pow(k, i)).toFixed(decimals));
return `${size} ${sizes[i]}`;
}
module.exports = fileSizePretty;