工具庫,封裝了處理arrays,numbers,objects,string等常見的函數,是對標準庫的補充。業務開發中經常使用的函數有不少,如:assign, times, debounce, get, find, filter, keyBy, cloneDeep, groupBy, omit, pick等。示例以下:javascript
const _ = require('lodash'); const obj = { name: 'zhangsan', age: 20, friends: [{ name: 'lisi', age: 18 }, { name: 'wanger', age: 19 }] }; // 深複製,等價於JSON.parse(JSON.stringify(obj)),可是JSON.parse的形式沒法複製函數 const obj2 = _.cloneDeep(obj); obj === obj2; // false // 深獲取屬性,業務開發中能夠取代if(a && a.b && a.b.c)的形式 _.get(obj, 'friends[0].age', 0); // 18 // extend properties _.assign({}, { name: 'zhangsan' }, { age: 20 }); // { name: 'zhangsan', age: 20 } // remove properties _.omit({ name: 'zhangsan', age: 20 }, ['age']); // { name: 'zhangsan'} // pick properties _.pick({ name: 'zhangsan', age: 20 }, ['age']); // { age: 20} const arr = [{ name: 'zhangsan', age: 20 }, { name: 'lisi', age: 19 }, { name: 'wanger', age: 18 } ]; _.keyBy(arr, 'name'); // { zhangsan: { name: 'zhangsan', age: 20 }, lisi: { name: 'lisi', age: 19 }, wanger: { name: 'wanger', age: 18 } } // debounce(消抖,中止的時候執行一次)和throttle(節流,每間隔必定時候執行一次) _.debounce(keyword => { console.log(keyword); }, 500); // N loop _.times(6, _.uniqueId.bind(null, 'key_')); // [ 'key_1', 'key_2', 'key_3', 'key_4', 'key_5', 'key_6' ] // 安全的JSON.parse function safeParse(str, defaultValue) { let result = _.attempt(function(str) { return JSON.parse(str) }, str) return _.isError(result) ? defalutValue : result } safeParse(JSON.stringify({ a: 1 }), {}); // { a: 1 }
js類型判斷庫,可判斷js中的類型,包括promise,generator等。示例以下:html
is.array([1]) // => true is.null(null) // => true is.undefined(undefined) // => true is.object({a: 1}) // => true
格式化處理數字。示例以下:java
const TEN_THOUSANDS = 10000 const HUNDRED_MILLION = 100000000 numeral(345333).format('0,0’) => ‘345,333’ // 整數處理 numeral(3.45333).format('0.00’) => ‘3.45' // 保留兩位小數 numeral(0.9756).format('0.00%’) => ’97.56%’ // 百分比處理 numeral(14321235334343).divide(HUNDRED_MILLION).format('0,0.00’) => ‘143,212.35億’ //億處理 numeral(143212353).divide(TEN_THOUSANDS).format('¥0,0.00') => '14,321.24'萬 //萬處理 // 格式化數字, 大於億的展現爲億,大於萬的展現爲萬... formatNum() { if(number > HUNDREND_MILLION) { return numeral(number).divide(HUNDREND_MILLION).format(‘0,0.00’) + ‘億' } else if(number > TEN_THOUSANDS) { return numeral(number).divide(TEN_THOUSANDS).format(‘0,0.00’) + ‘萬' } else { return numeral(number).format(‘0,0.00') } }
時間處理庫。示例以下:node
moment().format(‘YYYY-MM-DD')
excel-export庫,基於node.js將數據生成excel文件,生成格式爲xlsx。json
// json轉excel const nodeExcel = require('excel-export'); const _ = require('lodash'); const fs = require('co-fs'); const co = require('co'); /** * 使用場景: * 導出Excel * * 用法: * params: * - name: excel文件名稱 * - path: 導出的excel路徑 * * rows: * [ * { * name: '' * _created_at: '' * }, * ..... * ] * * cols: * [ * { * key: 'name', * text: '名稱' * }, * { * key: '_created_at', * text: '提交時間', * filter: dateStr => { * return dateStr.length === 0 ? dateStr : dateStr.split('.')[0].replace('T', ' '); * } * } * ]; */ function wrapConf(rows, cols) { let conf = {}; conf.name = 'sheet1'; conf.cols = cols.map(item => { return { caption: item.text, type: item.type || 'string', width: item.width || 20 }; }); conf.rows = rows.map((row) => { return cols.map((col) => { if (col.filter) { return col.filter(_.get(row, col.key), row); } else { return _.get(row, col.key); } }); }); return conf; } function* exportExcel(path, rows, cols) { let conf = wrapConf(rows, cols); // 配置項 let result = nodeExcel.execute(conf); // 導出excel return yield fs.writeFile(path, result, 'binary'); // 寫入到路徑 } module.exports = exportExcel;
js-xlsx庫,讀取和解析多種格式表格的js庫。promise
// excel轉json const fs = require('co-fs'); const co = require('co'); const XLSX = require('xlsx'); // { // SheetNames: ['sheet1', 'sheet2'], // Sheets: { // // worksheet // 'sheet1': { // // cell // 'A1': { ... }, // // cell // 'A2': { ... }, // ... // }, // // worksheet // 'sheet2': { // // cell // 'A1': { ... }, // // cell // 'A2': { ... }, // ... // } // } // } function toJson(workbook, keys) { let result = {}; let sheetNames = workbook.SheetNames; sheetNames.forEach(sheetName => { let worksheet = workbook.Sheets[sheetName]; result[sheetName] = XLSX.utils.sheet_to_json(worksheet, { header: keys }); }); return result; }; /** * * * @param {any} src: excel文件地址 * @param {any} dest: 導出json文件地址 * @param {any} keys: excel列名映射到json的keys * @returns */ function* excelToJson(src, dest, keys) { let data = yield fs.readFile(src) let json = toJson(XLSX.read(data)) return yield fs.writeFile(dest, JSON.stringify(json, 2, 2)) } module.exports = excelToJson;
markdown文件轉html文件,使用marked-toc(生成文件目錄),marked(markdown解析庫),hightlight(代碼高亮)。安全
const md5 = require('md5'); const markedToc = require('marked-toc'); const marked = require('marked'); const highlight = require('highlight'); const fs = require('fs'); function generateTocName(name) { name = name.trim().replace(/\s+/g, '').replace(/\)/g, '').replace(/[\(\,]/g, '-').toLowerCase(); if (/^[\w\-]+$/.test(name)) { return name; } return `toc-${md5(name).slice(0, 3)}`; } // filePath爲markdown文件目錄 function markdownToHtml(filePath) { let content = fs.readFileSync(filePath, 'utf8'); let tocContent = marked(markedToc(content)).replace(/<a\s+href="#([^\"]+)">([^<>]+)<\/a>/g, (a, b, c) => { return `<a href="#${generateTocName(c)}">${c}</a>`; }); let markedContent = marked(content).replace(/<h(\d)[^<>]*>(.*?)<\/h\1>/g, (a, b, c) => { if (b == 2) { return `<h${b} id="${generateTocName(c)}">${c}</h${b}>`; } return `<h${b} id="${generateTocName(c)}"><a class="anchor" href="#${generateTocName(c)}"></a>${c}</h${b}>`; }); markedContent = markedContent.replace(/<h(\d)[^<>]*>([^<>]+)<\/h\1>/, (a, b, c) => { return `${a}<div class="toc">${tocContent}</div>`; }); let highlightContent = markedContent.replace(/<pre><code\s*(?:class="lang-(\w+)")?>([\s\S]+?)<\/code><\/pre>/mg, (a, language, text) => { text = text.replace(/'/g, '\'').replace(/>/g, '>').replace(/</g, '<').replace(/\"/g, '"').replace(/\&/g, "&"); var result = highlight.highlightAuto(text, language ? [language] : undefined); return `<pre><code class="hljs lang-${result.language}">${result.value}</code></pre>`; }); return highlightContent; }