UNPKG

@irim/bin-tool

Version:

node bin tools

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