node-os-utils
Version:
Advanced cross-platform operating system monitoring utilities with TypeScript support
141 lines • 3.25 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.Timestamp = exports.DataSize = void 0;
/**
* 数据单位处理类
*/
class DataSize {
constructor(bytes) {
this.bytes = bytes;
if (bytes < 0) {
throw new Error('Data size cannot be negative');
}
}
/**
* 获取字节数
*/
toBytes() {
return this.bytes;
}
/**
* 转换为 KB
*/
toKB() {
return this.bytes / 1024;
}
/**
* 转换为 MB
*/
toMB() {
return this.bytes / (1024 * 1024);
}
/**
* 转换为 GB
*/
toGB() {
return this.bytes / (1024 * 1024 * 1024);
}
/**
* 转换为 TB
*/
toTB() {
return this.bytes / (1024 * 1024 * 1024 * 1024);
}
/**
* 自动选择合适的单位并格式化
*/
toString(unit) {
if (unit && unit !== 'auto') {
switch (unit) {
case 'B':
return `${this.bytes} B`;
case 'KB':
return `${this.toKB().toFixed(2)} KB`;
case 'MB':
return `${this.toMB().toFixed(2)} MB`;
case 'GB':
return `${this.toGB().toFixed(2)} GB`;
case 'TB':
return `${this.toTB().toFixed(2)} TB`;
}
}
// 自动选择单位
if (this.bytes < 1024) {
return `${this.bytes} B`;
}
else if (this.bytes < 1024 * 1024) {
return `${this.toKB().toFixed(2)} KB`;
}
else if (this.bytes < 1024 * 1024 * 1024) {
return `${this.toMB().toFixed(2)} MB`;
}
else if (this.bytes < 1024 * 1024 * 1024 * 1024) {
return `${this.toGB().toFixed(2)} GB`;
}
else {
return `${this.toTB().toFixed(2)} TB`;
}
}
/**
* 创建 DataSize 实例的静态方法
*/
static fromBytes(bytes) {
return new DataSize(bytes);
}
static fromKB(kb) {
return new DataSize(kb * 1024);
}
static fromMB(mb) {
return new DataSize(mb * 1024 * 1024);
}
static fromGB(gb) {
return new DataSize(gb * 1024 * 1024 * 1024);
}
}
exports.DataSize = DataSize;
/**
* 时间戳处理类
*/
class Timestamp {
constructor(time = Date.now()) {
this.time = time;
}
/**
* 距离现在多久(毫秒)
*/
ago() {
return Date.now() - this.time;
}
/**
* 格式化为 ISO 字符串
*/
format() {
return new Date(this.time).toISOString();
}
/**
* 格式化为本地时间字符串
*/
toLocalString() {
return new Date(this.time).toLocaleString();
}
/**
* 获取原始时间戳
*/
valueOf() {
return this.time;
}
/**
* 创建当前时间戳
*/
static now() {
return new Timestamp();
}
/**
* 从特定时间创建时间戳
*/
static from(time) {
return new Timestamp(typeof time === 'number' ? time : time.getTime());
}
}
exports.Timestamp = Timestamp;
//# sourceMappingURL=common.js.map