# co-util

> A collection of utilities for nodejs.

Latest version **2.1.18** (published 2025-03-03) · ISC license · 0 weekly downloads

## Install

```sh
npm install co-util
pnpm add co-util
yarn add co-util
bun add co-util
```

## Health

**Score 35/100 (D)** — status: maintenance-mode.

Positive: has types; no vulnerabilities; high quality score.

Warnings: low downloads; no esm support.

Negative: stale; low maintenance score.

## Facts

| | |
|---|---|
| Version | 2.1.18 |
| Published | 2025-03-03 |
| First published | 2016-11-14 |
| Weekly downloads | 0 |
| License | ISC |
| TypeScript types | bundled |
| Module format | CommonJS |
| Dependencies | 9 |
| Unpacked size | 68.4 KB |
| Known vulnerabilities | 0 (+1 in 1 direct dependencies) |
| Install scripts | no |
| GitHub stars | 4 |
| Author | codeorg.com |
| Maintainers | codeorg |
| Keywords | util, utility, typescript, codeorg.com |

## Links

- npm: https://www.npmjs.com/package/co-util
- Repository: https://github.com/codeorg/co-util
- Homepage: https://github.com/codeorg/co-util#readme
- Issues: https://github.com/codeorg/co-util/issues
- npm.io page: https://npm.io/package/co-util

## Dependencies (9)

- [uuid](https://npm.io/package/uuid.md) ^3.0.1
- [axios](https://npm.io/package/axios.md) ^1.8.0
- [lodash](https://npm.io/package/lodash.md) ^4.17.21
- [mkdirp](https://npm.io/package/mkdirp.md) ^0.5.1
- [moment](https://npm.io/package/moment.md) ^2.18.1
- [rimraf](https://npm.io/package/rimraf.md) ^2.6.1
- [archiver](https://npm.io/package/archiver.md) ^7.0.1
- [unzipper](https://npm.io/package/unzipper.md) ^0.10.11
- [https-proxy-agent](https://npm.io/package/https-proxy-agent.md) ^5.0.1

## Alternatives

- [@openai/codex-sdk](https://npm.io/package/@openai/codex-sdk.md) — 731.4K weekly downloads
- [babel-plugin-transform-react-jsx](https://npm.io/package/babel-plugin-transform-react-jsx.md) — 565.0K weekly downloads
- [babel-helper-remove-or-void](https://npm.io/package/babel-helper-remove-or-void.md) — 508.5K weekly downloads
- [@pnpm/store-controller-types](https://npm.io/package/@pnpm/store-controller-types.md) — 186.9K weekly downloads
- [react-native-signature-canvas](https://npm.io/package/react-native-signature-canvas.md) — 155.6K weekly downloads

## Recent versions

- 2.1.18 (latest) — 2025-03-03
- 2.1.16 — 2024-06-20
- 2.1.15 — 2024-01-26
- 2.1.14 — 2023-11-15
- 2.1.13 — 2023-08-09
- 2.1.12 — 2023-06-05
- 2.1.11 — 2023-06-05
- 2.1.10 — 2023-06-05
- 2.1.9 — 2023-06-05
- 2.1.8 — 2023-06-05
- 2.1.7 — 2023-03-02
- 2.1.6 — 2023-03-02
- 2.1.5 — 2023-02-21
- 2.1.4 — 2023-02-21
- 2.1.3 — 2023-02-12
- … 162 more at https://npm.io/package/co-util/versions

## README

# co-util
A collection of utilities for nodejs.
## Install
```git
npm i co-util
```
## Usage
```js
const util=require('co-util');
```
## http

### `util.http.setProxy('http://ip:port')`
设置全局代理

### `util.http.defaults.headers.common['Authorization'] = AUTH_TOKEN`
设置全局配置

### `util.http.get(url[,data][,options])`
建立一个http get请求,`url`为请求地址，`data`为请求数据，可省略

The optional `options` object may contain:
- `headers` (object?, default `'null'`): header头，如:`{Authorization:'Bearer ${token}'}`
- `httpAgent` (object?, default `'null'`):  define a custom agent to be used when performing http and https requests, respectively, in node.js. This allows options to be added like `keepAlive` that are not enabled by default.
- `timeout` (number?, default `0`): header头，如:`{'Content-Type':'application/x-www-form-urlencoded'}`


### `util.http.post(url,data[,options])`
建立一个http post请求,`url`为请求地址，`data`为请求数据，可省略,options 同上，默认为application/json

```js
let html = await util.http.get(url).catch(err => err);

let opts={
    headers:{'Content-Type':'application/x-www-form-urlencoded'}
    //默认为application/application/json
}

let html = await util.http.post(url,postData,opts).catch(err => err);
if (html instanceof Error) {
    //出错
}else{
    //To Do...
}
```

## filesystem
```js
util.fs.mkdir(path) //创建文件夹，同时创建上层目录
util.fs.rmrf(path) //删除整个目录包括子目录
util.fs.mv(src, dest) //移动文件
util.fs.ll(path) //获取所有文件和目录 返回 [{fullname:'',filename:'',stat:{}}]
util.fs.readDir(path) //获取当前目录下的文件夹和文件
util.fs.stat(path); //获取文件状态
util.fs.exist(path) //文件是否存在
util.fs.readFile(path) //读文件
util.fs.readGzip(path) //读gzip文件
util.fs.writeFile(path, body); //写入文件
util.fs.writeFile(path, str, { flag: 'a' }); //追加写入
util.fs.cp(src,dist,mode=0); //追加写入

```

## array
```js
util.chunk(['a', 'b', 'c', 'd'],2) //[2, 3, 4, 5]
util.drop([1, 2, 3, 4, 5]) //[2, 3, 4, 5]
util.dropRight([1, 2, 3, 4, 5]) //[1, 2, 3, 4]
util.xor([1, 2, 6], [1, 2, 3, 4, 5])//[6, 3, 4, 5] 异或，去除相同的，然后去重，所有的比较仅和第一个传参比较
util.notIn([1, 2, 3, 4, 5]，[1, 2, 5, 6])//[3, 4] 不包含，第一个参数里不包含之后所有参数的数组
util.concat([1, 2, 3], [2, 3]) //[1, 2, 3, 2, 3]
util.compact([0, 1, false, 2, '', 3]) //[1, 2, 3] 去除数组里空值
util.flatten([1, [2, [3, [4]], 5]]) //[1, 2, [3, [4]], 5] 把数组变平
util.values([{ 'user': 'barney' }, { 'user': 'fred' }],'user') //['barney', 'fred']获取集合里某个key对应的value数组
util.uniq([{n:1},{n:2},{n:1}] ) //[{n:1},{n:2}]去重
util.indexOf([1, 2, 3], 2) //1
util.findIndex([{ n: 1 }, { n: 2 }, { n: 3 }], { n: 3 }) //2
util.findOne([{ n: 1, b: 1 }, { n: 1, b: 2 }, { n: 3 }], { n: 1 }) //{ n: 1, b: 1 }
util.find([{ n: 1 }, { n: 2, a: 22 }, { n: 3 }], [{ n: 2 }])  //[{ n: 2, a: 22 }]
util.map([{a:1},{a:2}], 'a') //[1,2]
util.max([1, 2, 3, 4, 5])   //5
util.maxBy([{ n: 1, a: 2 }, { n: 2, a: 5 }, { n: 3, c: 1 }], 'n')  //{ n: 3, c: 1 }
util.min([1, 2, 3, 4, 5]) //1
util.minBy([{ n: 1, a: 2 }, { n: 2, a: 5 }, { n: 3, c: 1 }], 'n') //{ n: 1, a: 2 })
util.sort([5, 4, 3, 2, 1]) //[1, 2, 3, 4, 5]
util.sortRandom(arr) //数组随机，不改变arr的值
util.kv(arr,key) //把集合转化成以key为主键的对象,kv键值对，[{id:"key1",b:2},{id:"key2",b:3}]=>{"key1":{id:"key1",b:2},"key2":{id:"key2",b:3}}
```

## object
```js
util.is(value,other) //两个对象或者数组是否相等
util.isObject(value)
util.isPlainObject(value)
util.isJson(str)
util.isNullObj(obj)
util.extend(obj,[obj2...])
util.merge(obj,[obj2...])
util.formatObj(obj)
util.sortObj(obj)
util.sign(obj, key) //获取签名
util.default({ 'a': { 'b': 2 } }, { 'a': { 'b': 1, 'c': 3 } }) // { 'a': { 'b': 2, 'c': 3 } } 设置默认值，对没有设置过的option，给一个默认值，深度设置
util.pick({'a': 1, 'b': '2', 'c': 3 }, ['a', 'c']) //返回指定属性的对象 { 'a': 1, 'c': 3 }
```

## number
```js
util.isInt(value)
util.isNumber(value)
util.random(start,end)
util.round(value)
util.toInt(str)
util.toNumber(value)
util.formatMoney(value)
util.toFixed(num, bit) //0=>0,10.22=>10.2,9=>9
```

## string
```js
util.isString(value) //是否字符串类型
util.toJson(value) //字符串转化为json,如果转换失败则为空
util.uuid() //生成uuid
util.trim(value) //去除两边空格
util.formatIp(ip) //ip格式化
util.format(f,...val) //字符格式化
util.querystring(obj) //query string,value值进行encodeUrl
util.encodeUrl(value) //url encode
util.decodeUrl(value) //url decode
util.toText(html, length) //html转成text
util.camelCase(value) //返回驼峰命名
```

## datetime
```js
util.toDate(value)
util.isDate(value)
util.getTimeByObjectId(objectId) //把mongo的Object转成datetime
util.formatDate(value)
util.dayTime(date, inc) //保持到00:00:00
util.setDay(date, inc) //弃用，请使用dayTime
util.addDate(date, type, inc)
util.addSecond(date, inc)
util.addMinute(date, inc)
util.addHour(date, inc)
util.addDay(date, inc)
util.fromNow(start) //时差 (之前，现在为基准)
```

## zip
util.zip(src, dist, opts) 压缩文件

Options相关参数
- `'src'` - `string`类型，源文件
- `'dist'` - `string`类型，目标路径
- `'opts'` - `object`类型，选项
    - `'ignore'` - `array<string>`忽略文件夹或者文件 
                    如：["**/node_modules/**", "**/ *.log", "** /tmp/ **", "**/*.zip"]

util.unzip(src, dist) 解压覆盖文件

## other
```js
await util.sleep(100) //等待100ms
```

---
_Source: https://npm.io/package/co-util · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
