在 Node.js 中自动格式化大小字符串
问题:
在 NodeJS 中,你有一个以字节为单位的文件大小,但你想格式化它以提高可读性。
例如,如果你的大小是 10000 字节,你想打印 10 kilobytes,但如果是 1200000,你想打印 1.20 Megabytes。
解决方案
使用此函数:
autoFormatFilesize.js
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";
}
}此代码始终输出三位数字。 根据你处理的大小,你可能需要向列表添加 TB 甚至 PB,或者你可能需要更改输出的精度。
如果你正在寻找具有更多功能的现成库,请查看 bytes.js,你可以像这样使用:
bytes-example.js
const bytes = require('bytes');
console.log(bytes(1024)); //打印 "1 kB"
Check out similar posts by category:
C/C++
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow