imily-lodash
v0.0.66
Published
Readme
imily-lodash
基于 Lodash 的扩展库,包含了丰富的实用工具函数,适用于 Node.js 和 Web 环境。
安装
npm install imily-lodash引入
// Node.js
const _ = require('imily-lodash');
// ES Module
import _ from 'imily-lodash';扩展方法
除了 Lodash 原生的所有方法外,本库还扩展了以下实用方法:
HTTP 请求(Ajax)
_.httpGet(url, params, options, onlyData)
发起 HTTP GET 请求。
| 参数 | 类型 | 说明 |
|------|------|------|
| url | string | 请求地址 |
| params | object | URL 查询参数 |
| options | object | axios 配置项 |
| onlyData | boolean | 是否只返回 data(默认 true) |
返回值: Promise<any>
const data = await _.httpGet('https://api.example.com/users', { page: 1 });_.httpPost(url, body, options, onlyData)
发起 HTTP POST 请求。
| 参数 | 类型 | 说明 |
|------|------|------|
| url | string | 请求地址 |
| body | object | 请求体数据 |
| options | object | axios 配置项 |
| onlyData | boolean | 是否只返回 data(默认 true) |
返回值: Promise<any>
const result = await _.httpPost('https://api.example.com/login', { username: 'admin', password: '123456' });_.createAjax(baseURL, options, handleError)
创建自定义的 axios 实例。
| 参数 | 类型 | 说明 |
|------|------|------|
| baseURL | string | 基础 URL |
| options | object | axios 配置项 |
| handleError | boolean | 是否自动处理错误(默认 true) |
返回值: AxiosInstance
const api = _.createAjax('https://api.example.com');
const data = await api.get('/users');_.download(url, out, options) (仅 Node.js)
下载文件并保存到本地。
| 参数 | 类型 | 说明 |
|------|------|------|
| url | string | 下载地址 |
| out | string \| WriteStream | 输出路径或写入流 |
| options | object | 配置项 |
返回值: Promise<boolean>
await _.download('https://example.com/file.zip', './downloads/file.zip');_.getAxios()
获取原始的 axios 实例。
返回值: Axios
对象复制(Copy)
_.copy(val)
深度复制对象(支持循环引用)。
| 参数 | 类型 | 说明 |
|------|------|------|
| val | any | 要复制的值 |
返回值: 复制后的值
const obj = { a: 1, b: { c: 2 } };
const copied = _.copy(obj);_.copy2(val)
使用 JSON 序列化进行简单对象复制(不支持循环引用、函数等)。
| 参数 | 类型 | 说明 |
|------|------|------|
| val | any | 要复制的值 |
返回值: 复制后的值
const copied = _.copy2({ a: 1 });加密与脱敏(Crypto)
_.md5(input)
计算字符串的 MD5 值。
| 参数 | 类型 | 说明 |
|------|------|------|
| input | string | 输入字符串 |
返回值: string - 32位 MD5 哈希值
const hash = _.md5('hello world');_.md5file(file) (仅 Node.js)
计算文件的 MD5 值。
| 参数 | 类型 | 说明 |
|------|------|------|
| file | string \| Buffer | 文件路径或 Buffer |
返回值: string - 32位 MD5 哈希值
const hash = _.md5file('./package.json');_.md5fileAsync(file, timeout) (仅 Node.js)
异步计算文件的 MD5 值(适用于大文件)。
| 参数 | 类型 | 说明 |
|------|------|------|
| file | string | 文件路径 |
| timeout | number | 超时时间(默认 10 分钟) |
返回值: Promise<string>
_.maskPhone(number, replaceChar)
手机号码脱敏,保留后 4 位。
| 参数 | 类型 | 说明 |
|------|------|------|
| number | string \| number | 手机号码 |
| replaceChar | string | 替换字符(默认 *) |
返回值: string
_.maskPhone('13812345678'); // '*******5678'_.maskEmail(email, replaceChar)
邮箱地址脱敏。
| 参数 | 类型 | 说明 |
|------|------|------|
| email | string | 邮箱地址 |
| replaceChar | string | 替换字符(默认 *) |
返回值: string
_.maskEmail('[email protected]'); // '***@example.com'_.encryptAES(data, key) (仅 Node.js)
AES-128-CBC 加密。
| 参数 | 类型 | 说明 |
|------|------|------|
| data | string | 待加密数据 |
| key | string | 密钥(32 位,前 16 位为 key,后 16 位为 iv) |
返回值: string - Base64 编码的加密结果
const encrypted = _.encryptAES('hello', 'your-32-char-key-here...........');_.decryptAES(dataStr, key) (仅 Node.js)
AES-128-CBC 解密。
| 参数 | 类型 | 说明 |
|------|------|------|
| dataStr | string | Base64 编码的加密数据 |
| key | string | 密钥 |
返回值: string - 解密后的原文
const decrypted = _.decryptAES(encrypted, 'your-32-char-key-here...........');文件操作(File)(仅 Node.js)
_.glob(pattern, options)
枚举文件/文件夹(基于 fast-glob)。
| 参数 | 类型 | 说明 |
|------|------|------|
| pattern | string | glob 匹配模式 |
| options | object | 配置项(sync: true 可同步执行) |
返回值: Promise<string[]> 或 string[](同步模式)
const files = await _.glob('./src/**/*.js');_.readExcel(input)
读取 Excel 文件。
| 参数 | 类型 | 说明 |
|------|------|------|
| input | string \| stream | 文件路径或流 |
返回值: 包含以下方法的对象:
sheetNames()- 获取所有工作表名称cells(sheet, skipRows)- 获取单元格对象values(sheet, skipRows)- 获取单元格值texts(sheet, skipRows)- 获取单元格文本
const excel = await _.readExcel('./data.xlsx');
const names = excel.sheetNames();
const data = excel.values(1, 1); // 读取第1个工作表,跳过1行_.writeExcel(output, data)
写入 Excel 文件。
| 参数 | 类型 | 说明 |
|------|------|------|
| output | string \| stream | 输出路径或流 |
| data | array \| function | 二维数组数据或自定义处理函数 |
返回值: Promise<void>
await _.writeExcel('./output.xlsx', [
['姓名', '年龄'],
['张三', 25],
['李四', 30]
]);_.archiver(files, out)
压缩文件为 ZIP 格式。
| 参数 | 类型 | 说明 |
|------|------|------|
| files | string \| array | 文件/目录路径或对象数组 |
| out | string \| WriteStream | 输出路径或写入流 |
返回值: Promise<void>
// 压缩单个文件
await _.archiver('./file.txt', './archive.zip');
// 压缩多个文件
await _.archiver([
{ file: './file1.txt', name: 'file1.txt' },
{ file: './file2.txt', name: 'file2.txt' }
], './archive.zip');_.unArchiver(zipFile, callback)
解压 ZIP 文件。
| 参数 | 类型 | 说明 |
|------|------|------|
| zipFile | string \| Buffer \| stream | ZIP 文件路径、Buffer 或流 |
| callback | function | 处理回调(可选) |
返回值: Promise<Directory>
const directory = await _.unArchiver('./archive.zip');_.packFile(targetPath, destFile, winrarExe)
使用 WinRAR 打包文件。
| 参数 | 类型 | 说明 |
|------|------|------|
| targetPath | string | 要打包的路径 |
| destFile | string | 目标文件 |
| winrarExe | string | WinRAR 路径(默认 C:/Program Files/WinRAR/winrar.exe) |
返回值: Promise<string>
_.unPackFile(packFilePath, winrarExe)
使用 WinRAR 解压文件。
| 参数 | 类型 | 说明 |
|------|------|------|
| packFilePath | string | 压缩文件路径 |
| winrarExe | string | WinRAR 路径 |
返回值: Promise<string>
_.gzip(buf)
Gzip 压缩。
| 参数 | 类型 | 说明 |
|------|------|------|
| buf | Buffer | 要压缩的数据 |
返回值: Promise<Buffer>
_.gunzip(buf)
Gzip 解压。
| 参数 | 类型 | 说明 |
|------|------|------|
| buf | Buffer | 压缩的数据 |
返回值: Promise<Buffer>
格式化(Format)
_.sayEnglish(number)
将数字转换为英文大写表示。
| 参数 | 类型 | 说明 |
|------|------|------|
| number | number | 数字 |
返回值: string
_.sayEnglish(1234); // 'ONE THOUSAND,TWO HUNDRED AND THIRTY-FOUR'_.sayMoney(n, opt)
将人民币金额转换为中文大写。
| 参数 | 类型 | 说明 |
|------|------|------|
| n | number | 金额 |
| opt | object | 配置项 |
返回值: string
_.sayMoney(1234.56); // '壹仟贰佰叁拾肆元伍角陆分'_.pascalCase(word)
将字符串转换为 PascalCase(首字母大写驼峰命名)。
| 参数 | 类型 | 说明 |
|------|------|------|
| word | string | 输入字符串 |
返回值: string
_.pascalCase('hello_world'); // 'HelloWorld'
_.pascalCase('hello-world'); // 'HelloWorld'_.thousand(source, fractionDigits)
数字添加千分位分隔符。
| 参数 | 类型 | 说明 |
|------|------|------|
| source | number | 数字 |
| fractionDigits | number | 小数位数(默认 2) |
返回值: string
_.thousand(1234567.89); // '1,234,567.89'函数工具(Function)
_.isAsyncFunc(fn)
判断是否为异步函数。
| 参数 | 类型 | 说明 |
|------|------|------|
| fn | function | 函数 |
返回值: boolean
_.isAsyncFunc(async () => {}); // true
_.isAsyncFunc(() => {}); // false_.queue(asyncFn, concurrency, timeout)
创建并发队列执行器。
| 参数 | 类型 | 说明 |
|------|------|------|
| asyncFn | function | 异步函数 |
| concurrency | number | 并发数(默认 1) |
| timeout | number | 超时时间(默认 30000ms) |
返回值: 队列执行函数
const queuedFn = _.queue(async (id) => {
return await fetchData(id);
}, 5, 10000);
await queuedFn(1);_.mapLimit(data, asyncFn, concurrency)
并发限制的异步 map 操作。
| 参数 | 类型 | 说明 |
|------|------|------|
| data | array | 数据数组 |
| asyncFn | function | 异步处理函数 (item, index) => Promise |
| concurrency | number | 并发数(默认 10) |
返回值: Promise<array>
const results = await _.mapLimit([1, 2, 3, 4, 5], async (item, index) => {
return item * 2;
}, 2);_.retryable(asyncFn, times, interval)
创建可重试的异步函数。
| 参数 | 类型 | 说明 |
|------|------|------|
| asyncFn | function | 异步函数 |
| times | number | 重试次数(默认 3) |
| interval | number | 重试间隔(默认 0ms) |
返回值: 包装后的函数
const retryFn = _.retryable(async () => {
return await unstableApi();
}, 3, 1000);_.assert(val, error, code)
断言,如果 val 为假值则抛出错误。
| 参数 | 类型 | 说明 |
|------|------|------|
| val | any | 要判断的值 |
| error | string \| function | 错误信息或返回错误信息的函数 |
| code | any | 错误代码(可选) |
_.assert(user, '用户不存在', 404);_.error(err, code)
创建标准化的 Error 对象。
| 参数 | 类型 | 说明 |
|------|------|------|
| err | string \| Error \| object | 错误信息 |
| code | any | 错误代码 |
返回值: Error
throw _.error('操作失败', 500);_.lazyload(require)
模块懒加载工具。
| 参数 | 类型 | 说明 |
|------|------|------|
| require | function | require 函数 |
返回值: 懒加载函数
const lazy = _.lazyload(require);
const fs = lazy('fs'); // 首次使用时才会加载_.promiseAll(values)
增强版 Promise.all,等待所有 Promise 完成后返回结果,如有错误则抛出第一个错误。
| 参数 | 类型 | 说明 |
|------|------|------|
| values | array | Promise 数组 |
返回值: Promise<array>
const results = await _.promiseAll([promise1, promise2, promise3]);_.spawn(evalCode, args, timeout) (仅 Node.js)
在独立虚拟机中执行代码。
| 参数 | 类型 | 说明 |
|------|------|------|
| evalCode | string | 要执行的代码字符串 |
| args | any | 传入的参数 |
| timeout | number | 超时时间(默认 2 分钟) |
返回值: Promise<any>
_.sleep(wait)
异步等待指定时间。
| 参数 | 类型 | 说明 |
|------|------|------|
| wait | number | 等待时间(毫秒) |
返回值: Promise<void>
await _.sleep(1000); // 等待 1 秒_.catchError(func)
捕获函数执行的错误,返回 [error, result] 格式。
| 参数 | 类型 | 说明 |
|------|------|------|
| func | function \| Promise | 函数或 Promise |
返回值: [Error | null, any]
const [err, result] = await _.catchError(async () => {
return await someAsyncOperation();
});
if (err) {
console.error('操作失败:', err);
}_.asize(arr)
获取数组长度(安全方法,非数组返回 0)。
| 参数 | 类型 | 说明 |
|------|------|------|
| arr | array | 数组 |
返回值: number
_.asize([1, 2, 3]); // 3
_.asize(null); // 0
_.asize('abc'); // 0数字工具(Number)
_.equal(a, b)
浮点数相等比较(处理精度问题)。
| 参数 | 类型 | 说明 |
|------|------|------|
| a | number | 数字 a |
| b | number | 数字 b |
返回值: boolean
_.equal(0.1 + 0.2, 0.3); // true_.randomStr(len, toLower)
生成随机字符串。
| 参数 | 类型 | 说明 |
|------|------|------|
| len | number | 长度 |
| toLower | boolean | 是否只使用小写字母(默认 false) |
返回值: string
_.randomStr(8); // 'aB3xY9kM'
_.randomStr(8, true); // 'ab3xy9km'_.roundSumBy(items, func, precision)
四舍五入求和。
| 参数 | 类型 | 说明 |
|------|------|------|
| items | array | 数组 |
| func | function \| string | 迭代器 |
| precision | number | 精度(默认 3) |
返回值: number
_.roundSumBy([{ v: 1.111 }, { v: 2.222 }], 'v', 2); // 3.33_.floorSumBy(items, func, precision)
向下取整求和。
| 参数 | 类型 | 说明 |
|------|------|------|
| items | array | 数组 |
| func | function \| string | 迭代器 |
| precision | number | 精度(默认 3) |
返回值: number
_.ceilSumBy(items, func, precision)
向上取整求和。
| 参数 | 类型 | 说明 |
|------|------|------|
| items | array | 数组 |
| func | function \| string | 迭代器 |
| precision | number | 精度(默认 3) |
返回值: number
_.makeGroupItems(data, groupFunc, transFunc)
分组聚合数据。
| 参数 | 类型 | 说明 |
|------|------|------|
| data | array | 数据数组 |
| groupFunc | function \| string | 分组函数 |
| transFunc | function | 转换函数(可选) |
返回值: array - [{ group, items }, ...]
const data = [
{ type: 'A', value: 1 },
{ type: 'A', value: 2 },
{ type: 'B', value: 3 }
];
_.makeGroupItems(data, 'type');
// [{ group: 'A', items: [...] }, { group: 'B', items: [...] }]_.makeMap(data, keyFunc, valFunc)
从数组创建 Map。
| 参数 | 类型 | 说明 |
|------|------|------|
| data | array | 数据数组 |
| keyFunc | function \| string | 键函数 |
| valFunc | function | 值函数 |
返回值: Map
const users = [{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }];
const map = _.makeMap(users, 'id', v => v.name);
// Map { 1 => 'Alice', 2 => 'Bob' }_.makeGroupMap(data, keyFunc, valFunc)
从数组创建分组 Map(值为数组)。
| 参数 | 类型 | 说明 |
|------|------|------|
| data | array | 数据数组 |
| keyFunc | function \| string | 键函数 |
| valFunc | function | 值函数 |
返回值: Map - 值为数组
_.eachAssign(total, items, assignFunc, options)
迭代分配数量。
| 参数 | 类型 | 说明 |
|------|------|------|
| total | number | 待分配总量 |
| items | array | 项目数组 |
| assignFunc | function | 分配函数 (remaining, item, index) => assignedAmount |
| options | object | { reverse, precision } |
返回值: number - 剩余未分配数量
_.allocTotal(items, total, totalProp, options) / _.sliceTotal
按总量分配数据(切片)。
| 参数 | 类型 | 说明 |
|------|------|------|
| items | array | 项目数组 |
| total | number | 待分配总量 |
| totalProp | function \| string | 获取每项总量的函数 |
| options | object | { skip, precision } |
返回值: array - [[item, allocatedAmount], ...]
const items = [
{ name: 'A', count: 10 },
{ name: 'B', count: 20 }
];
_.allocTotal(items, 15, 'count');
// [[{ name: 'A', count: 10 }, 10], [{ name: 'B', count: 20 }, 5]]_.allocWeight(items, total, weightProp, precision)
按权重分配数量。
| 参数 | 类型 | 说明 |
|------|------|------|
| items | array | 项目数组 |
| total | number | 待分配总量 |
| weightProp | function \| string | 获取权重的函数 |
| precision | number | 精度(默认 0) |
返回值: array - [[item, allocatedAmount], ...]
const items = [
{ name: 'A', weight: 1 },
{ name: 'B', weight: 3 }
];
_.allocWeight(items, 100, 'weight');
// [[{ name: 'A', weight: 1 }, 25], [{ name: 'B', weight: 3 }, 75]]_.significant(num, precision)
返回四舍五入到指定有效数字的数字。
| 参数 | 类型 | 说明 |
|------|------|------|
| num | number | 要四舍五入的数字 |
| precision | number | 有效数字位数(默认 3) |
返回值: number
_.significant(0.001234, 3); // 0.00123
_.significant(1234.5678, 3); // 1234.568平台说明
- 通用方法:可在 Node.js 和 Web 环境中使用
- Node.js 专用:标注 (仅 Node.js) 的方法仅在 Node.js 环境可用
- Web 版本会自动使用相应的 Web 兼容实现
依赖
- lodash - 核心工具库
- axios - HTTP 客户端
- async-es - 异步控制流
- clone - 深拷贝
- fast-glob - 文件匹配
- archiver - ZIP 压缩
- unzipper - ZIP 解压
- imily-exceljs - Excel 读写
License
MIT © imily.net
