@supercharge/fs
Version:
Async filesystem methods for Node.js
85 lines (84 loc) • 2.55 kB
JavaScript
'use strict';
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.FileSizeBuilder = void 0;
const fs_extra_1 = __importDefault(require("fs-extra"));
class FileSizeBuilder {
/**
* Create a new instance for the given `filePath`.
*/
constructor(filePath) {
this.metric = 'bytes';
this.filePath = filePath;
}
async inBytes() {
return await this.setMetric('bytes').calculate();
}
async inKb() {
return await this.setMetric('kilobytes').calculate();
}
async inMb() {
return await this.setMetric('megabytes').calculate();
}
async inGb() {
return await this.setMetric('gigabytes').calculate();
}
async inTb() {
return await this.setMetric('terabytes').calculate();
}
async inPb() {
return await this.setMetric('petabytes').calculate();
}
setMetric(metric) {
this.metric = metric;
return this;
}
/**
* Returns the file size with the provided metric ("bytes" by default).
*/
then(onfulfilled, onrejected) {
return this.calculate()
.then(size => onfulfilled(size))
.catch(error => onrejected(error));
}
async calculate() {
const stats = await fs_extra_1.default.stat(this.filePath);
return this.convert(stats.size);
}
convert(bytes) {
switch (this.metric) {
case 'bytes':
return bytes;
case 'kilobytes':
return this.toKilobytes(bytes);
case 'megabytes':
return this.toMegabytes(bytes);
case 'gigabytes':
return this.toGigabytes(bytes);
case 'terabytes':
return this.toTerabytes(bytes);
case 'petabytes':
return this.toPetabytes(bytes);
default:
throw new Error(`Invalid file size metric. Received "${String(this.metric)}"`);
}
}
toKilobytes(bytes) {
return bytes / 1024;
}
toMegabytes(bytes) {
return this.toKilobytes(bytes) / 1024;
}
toGigabytes(bytes) {
return this.toMegabytes(bytes) / 1024;
}
toTerabytes(bytes) {
return this.toGigabytes(bytes) / 1024;
}
toPetabytes(bytes) {
return this.toTerabytes(bytes) / 1024;
}
}
exports.FileSizeBuilder = FileSizeBuilder;