slog-progress
Version:
nodejs简单的进度条
86 lines (85 loc) • 3.9 kB
JavaScript
;
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
if (ar || !(i in from)) {
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
ar[i] = from[i];
}
}
return to.concat(ar || Array.prototype.slice.call(from));
};
Object.defineProperty(exports, "__esModule", { value: true });
var single_line_log_1 = require("single-line-log");
var replace = function (str, token, value) {
return str.replace(new RegExp(":" + token, "g"), value);
};
var SlogBar = /** @class */ (function () {
/**
*
* @param {string} description 描述文字和占位符
* @param {object | number} options 配置或进度条长度
*/
function SlogBar(description, options) {
if (description === void 0) { description = "Loading..."; }
this.description = description; // 描述文字
if (typeof options == "number") {
this.length = options || 50; // 进度条的长度(单位:字符),默认设为 50
this.incomplete = "░"; // 没完成的进度占位符
this.complete = "█"; // 已完成的进度占位符
}
else if (options instanceof Object && Object.prototype.toString.call(options) === "[object Object]") {
this.length = options.width || 50;
this.incomplete = options.incomplete || "░"; // 没完成的进度占位符
this.complete = options.complete || "█"; // 已完成的进度占位符
}
else {
this.length = 50;
this.incomplete = "░"; // 没完成的进度占位符
this.complete = "█"; // 已完成的进度占位符
}
}
SlogBar.prototype.render = function (arg) {
var _this = this;
try {
var _a = arg.current, current = _a === void 0 ? 0 : _a, _b = arg.total, total = _b === void 0 ? 10 : _b;
if (total <= 0 || isNaN(total) || isNaN(current)) {
return false;
}
var currNum_1 = Math.floor((current / total) * this.length); // 计算需要多少个 █ 符号来拼凑图案
var bar = __spreadArray([], new Array(this.length), true).map(function (m, i) {
if (i <= currNum_1 - 1) {
return _this.complete;
}
return _this.incomplete;
})
.join("");
var percent = ((current / total) * 100).toFixed(2) + "%";
var exclude = ["bar", "percent"]; //不接收这些特殊的token
var text_1 = this.description;
var keyArr = [];
for (var key in arg) {
if (Object.hasOwnProperty.call(arg, key) && !exclude.includes(key)) {
keyArr.push([key, arg[key]]);
}
}
// 排一下序,优先匹配key比较长的,例如 :total和:totalFormat,优先匹配:totalFormat,不然会出现100Format的情况,匹配了total,Format就保留了,主要防止出现多个token,前面或后面一截相同的情况,优先匹配长的token
keyArr
.sort(function (a, b) {
return b[0].length - a[0].length;
})
.forEach(function (_a) {
var key = _a[0], val = _a[1];
text_1 = replace(text_1, key, val);
});
text_1 = replace(text_1, "percent", percent);
text_1 = replace(text_1, "current", current);
text_1 = replace(text_1, "total", total);
text_1 = replace(text_1, "bar", bar);
// 在单行输出文本
(0, single_line_log_1.stdout)(text_1);
}
catch (_c) { }
};
return SlogBar;
}());
exports.default = SlogBar;