ufiber
Version:
Next-gen webserver for node-js developer
33 lines (32 loc) • 814 B
JavaScript
//#region src/utils/tools.ts
/**
* Convert bytes to human readable format
*/
const formatBytes = (bytes) => {
if (bytes === 0) return "0B";
const k = 1024;
const sizes = [
"B",
"KB",
"MB",
"GB"
];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return `${(bytes / Math.pow(k, i)).toFixed(1)}${sizes[i]}`;
};
const parseBytes = (value) => {
const units = {
B: 0,
KB: 1,
MB: 2,
GB: 3
};
const match = value.trim().toUpperCase().match(/^([\d.]+)\s*(B|KB|MB|GB)$/);
if (!match) throw new Error(`Invalid byte format: "${value}"`);
const num = parseFloat(match[1]);
const unit = match[2];
return Math.round(num * Math.pow(1024, units[unit]));
};
const isPromise = (value) => value != null && typeof value.then === "function";
//#endregion
export { formatBytes, isPromise, parseBytes };