Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
U

utility

> 编程语言
Open source

A collection of useful utilities.

1.2K stars0 likes0 views
WebsiteGitHub

About

A collection of useful utilities.

utility

[![NPM version][npm-image]][npm-url] [![Test coverage][codecov-image]][codecov-url] [![npm download][download-image]][download-url] [npm-image]: https://img.shields.io/npm/v/utility.svg?style=flat-square [npm-url]: https://npmx.dev/package/utility [codecov-image]: https://codecov.io/github/node-modules/utility/coverage.svg?branch=master [codecov-url]: https://codecov.io/github/node-modules/utility?branch=master [download-image]: https://img.shields.io/npm/dm/utility.svg?style=flat-square [download-url]: https://npmx.dev/package/utility

A collection of useful utilities.

Install

bash
npm install utility

Usage

javascript
const utils = require('utility');

Also you can use it within typescript, like this ↓

typescript
import * as utils from 'utility';

md5

typescript
import { md5 } from 'utility';

md5('苏千');
// '5f733c47c58a077d61257102b2d44481'

md5(Buffer.from('苏千'));
// '5f733c47c58a077d61257102b2d44481'

// md5 base64 format
md5('苏千', 'base64'); 
// 'X3M8R8WKB31hJXECstREgQ=='

// Object md5 hash. Sorted by key, and JSON.stringify. See source code for detail
md5({foo: 'bar', bar: 'foo'}).should.equal(md5({bar: 'foo', foo: 'bar'}));

sha1

typescript
import { sha1 } from 'utility';

sha1('苏千');
// '0a4aff6bab634b9c2f99b71f25e976921fcde5a5'

sha1(Buffer.from('苏千'));
// '0a4aff6bab634b9c2f99b71f25e976921fcde5a5'

// sha1 base64 format
sha1('苏千', 'base64');
// 'Ckr/a6tjS5wvmbcfJel2kh/N5aU='

// Object sha1 hash. Sorted by key, and JSON.stringify. See source code for detail
sha1({foo: 'bar', bar: 'foo'}).should.equal(sha1({bar: 'foo', foo: 'bar'}));

sha256

typescript
import { sha256 } from 'utility';

sha256(Buffer.from('苏千'));
// '75dd03e3fcdbba7d5bec07900bae740cc8e361d77e7df8949de421d3df5d3635'

hmac

typescript
import { hmac } from 'utility';

// hmac-sha1 with base64 output encoding
hmac('sha1', 'I am a key', 'hello world');
// 'pO6J0LKDxRRkvSECSEdxwKx84L0='

decode and encode

…

others

[WARNNING] getIP() remove, PLEASE use https://github.com/node-modules/address module instead.

javascript
// get a function parameter's names
utils.getParamNames(function (key1, key2) {}); // ['key1', 'key2']

// get a random string, default length is 16.
utils.randomString(32, '1234567890'); //18774480824014856763726145106142

// check if object has this property
utils.has({hello: 'world'}, 'hello'); //true

// empty function
utils.noop = function () {}

// throw out an assertion error if you were given an invalid "func"
try {
  utils.getParamNames(null); // Only function is allowed
} catch (err) {
  console.error(err); // Assertion Error
}

Date utils

…

Number utils

javascript
// Detect a number string can safe convert to Javascript Number.: `-9007199254740991 ~ 9007199254740991`
utils.isSafeNumberString('9007199254740991'); // true
utils.isSafeNumberString('9007199254740993'); // false

// Convert string to number safe:
utils.toSafeNumber('9007199254740991'); // 9007199254740991
utils.toSafeNumber('9007199254740993'); // '9007199254740993'

// Produces a random integer between the inclusive `lower` and exclusive `upper` bounds.
utils.random(100); // [0, 100)
utils.random(2, 1000); // [2, 1000)
utils.random(); // 0

Timeout

runWithTimeout(scope, timeout)

Executes a scope promise with a specified timeout duration. If the promise doesn't resolve within the timeout period, it will reject with a TimeoutError.

typescript
import { runWithTimeout } from 'utility';

await runWithTimeout(async () => {
  // long run operation here
}, 1000);

map

Create a real map in javascript.

use Object.create(null)

javascript
const map = utils.map({a: 1});

// should.not.exist(map.constructor);
// should.not.exist(map.__proto__);
// should.not.exist(map.toString);
// should not exist any property

console.log(map); // {a: 1}

String utils

javascript
// split string by sep
utils.split('foo,bar,,,', ','); // ['foo', 'bar']

// replace string work with special chars which `String.prototype.replace` can't handle
utils.replace(' hi', '', '$& body'); // '$& body hi'

// replace http header invalid characters
utils.replaceInvalidHttpHeaderChar('abc你好11'); // {invalid: true, val: 'abc  11'}

Try

javascript
const res = utils.try(function () {
  return JSON.parse(str);
});

// {error: undefined, value: {foo: 'bar'}}
// {error: Error, value: undefined}

Note that when you use typescript, you must use the following methods to call ' Try '

javascript
import { UNSTABLE_METHOD } from 'utility';

UNSTABLE_METHOD.try(...);
...

argumentsToArray

javascript
function foo() {
  const arr = utils.argumentsToArray(arguments);
  console.log(arr.join(', '));
}

JSON

javascript
const obj = utils.strictJSONparse('"hello"');
// will throw when JSON string is not object

const pkg = utils.readJSONSync('package.json');
utils.writeJSONSync('package.json', pkg, {
  replacer: null,
  space: '\t',
});

Or you can use async API

javascript
async () => {
  const pkg = await utils.readJSON('package.json');
  await utils.writeJSON('package.json', pkg);
}

Hint: In utils.writeJSON*(), if pkg is an object, the optional third parameter options may contain two keys.

  • replacer: Equals to JSON.stringify()'s second parameter;
  • space: Equals to JSON.stringify()'s third parameter. Defaults to 2.

Refs:

Object.assign

javascript
// assign object
utils.assign({}, { a: 1 });

// assign multiple object
utils.assign({}, [ { a: 1 }, { b: 1 } ]);

benchmark

  • jsperf: access log date format
  • benchmark/date_format.js
…

benchmark/date_YYYYMMDD.js

bash
$ node benchmark/date_YYYYMMDD.cjs

parseInt(moment().format("YYYYMMDD"), 10): 20130416
utils.datestruct().YYYYMMDD: 20130416
new Date().toString(): "Tue Apr 16 2013 21:12:02 GMT+0800 (CST)"
------------------------
parseInt(moment().format('YYYYMMDD'), 10) x 129,604 ops/sec ±0.46% (101 runs sampled)
utils.datestruct().YYYYMMDD x 2,317,461 ops/sec ±1.38% (95 runs sampled)
new Date().toString() x 816,731 ops/sec ±3.46% (93 runs sampled)
Fastest is utils.datestruct().YYYYMMDD

License

MIT

Contributors

Made with contributors-img.

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

TypeScript

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category编程语言
PricingOpen source

> Related tools

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言