@irim/bin-tool
Version:
node bin tools
114 lines (113 loc) • 3.33 kB
JavaScript
;
// piece utils
// @author Pluto <huarse@gmail.com>
// @create 2020/05/14 10:45
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const chalk_1 = __importDefault(require("chalk"));
const dateformat_1 = __importDefault(require("dateformat"));
const properties_1 = __importDefault(require("properties"));
function logger(...args) {
// eslint-disable-next-line
console.log(...args);
}
exports.logger = logger;
const LOG_TYPES = { 'debug': 'gray', 'info': 'cyan', 'success': 'green', 'warn': 'yellow', 'error': 'red' };
/**
* print console log
* @param type 日志类型
* @param msg 日志内容
*/
function print(type, msg) {
const c = LOG_TYPES[type];
const now = new Date();
let _ss = (+now) % 1e3 + '';
_ss = ((1e3 + _ss) + '').substring(1);
logger(chalk_1.default.gray('[' + dateformat_1.default(now, 'HH:MM:ss.') + _ss + ']'), chalk_1.default[c](msg));
}
exports.print = print;
/**
* print JSON to console
*/
function printJSON(json) {
for (const key in json) {
if (Object.prototype.hasOwnProperty.call(json, key)) {
const value = json[key];
logger(`- ${key}: ${chalk_1.default.green(value)}`);
}
}
}
exports.printJSON = printJSON;
/**
* 睡眠 xx 毫秒
* @param millseconds 毫秒
*/
function sleep(millseconds) {
return new Promise(resolve => {
setTimeout(() => resolve(), millseconds);
});
}
exports.sleep = sleep;
/**
* 解析 .properties 文件,返回一个 JSON
* @param file 文件地址
*/
async function parseProperties(file) {
return new Promise((resolve, reject) => {
properties_1.default.parse(file, { path: true, sections: true }, (err, obj) => {
if (err)
return reject(err);
resolve(obj);
});
});
}
exports.parseProperties = parseProperties;
/**
* 返回一个进度条 string
*/
function getProgressStr(recent, total, label) {
if (!total && recent <= 1) {
total = 100;
recent = Math.round(recent * 100);
}
const percent = recent / total;
let pieceCount = Math.round(percent * 40);
let leftCount = 40 - pieceCount;
let str = '';
while (pieceCount-- > 0)
str += '◼︎';
while (leftCount-- > 0)
str += '◻︎';
let bar;
if (percent < 0.3) {
bar = chalk_1.default.gray(str);
}
else if (percent < 0.8) {
bar = chalk_1.default.yellow(str);
}
else {
bar = chalk_1.default.green(str);
}
return `${label || 'processing...'} ${bar} ${recent} / ${total} \n`;
}
exports.getProgressStr = getProgressStr;
/**
* 从对象中解析出想要的值
* @example
* parseValue({ a: [{ b: 100 }] }, 'a.0.b'); // 100
*/
function parseValue(data = {}, key) {
return key.split('.').reduce((prev, curr) => prev && prev[curr] || undefined, data);
}
exports.parseValue = parseValue;
/**
* 最简单的模板渲染
* @param tpl 模板,变量用 {{xxx}}表示
* @param data 渲染的数据
*/
function templateRender(tpl, data = {}) {
return tpl.replace(/\{\{\s?([a-z_$]+)\s?\}\}/gi, (_, key) => parseValue(data, key));
}
exports.templateRender = templateRender;