Detalhes do pacote

utility

node-modules1.2mMIT2.5.0

A collection of useful utilities.

utility, util, utils, sha256

readme (leia-me)

utility

NPM version CI Test coverage npm download Node.js Version PRs Welcome

A collection of useful utilities.

Install

npm install utility

Usage

const utils = require('utility');

Also you can use it within typescript, like this ↓

import * as utils from 'utility';

md5

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

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

import { sha256 } from 'utility';

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

hmac

import { hmac } from 'utility';

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

decode and encode

import { base64encode, base64decode, escape, unescape, encodeURIComponent, decodeURIComponent } from 'utility';

// base64 encode
base64encode('你好¥');
// '5L2g5aW977+l'
base64decode('5L2g5aW977+l');
// '你好¥'

// urlsafe base64 encode
base64encode('你好¥', true);
// '5L2g5aW977-l'
base64decode('5L2g5aW977-l', true);
// '你好¥'

// html escape and unescape
escape('<script/>"& &amp;');
// '&lt;script/&gt;&quot;&amp; &amp;amp;'
unescape('&lt;script/&gt;&quot;&amp; &amp;amp;');
// '<script/>"& &amp;'

// Safe encodeURIComponent and decodeURIComponent
decodeURIComponent(encodeURIComponent('你好, Node.js'));
// '你好, Node.js'

others

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

// 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

// accessLogDate
utils.accessLogDate(); // '16/Apr/2013:16:40:09 +0800'

// logDate,
// 'YYYY-MM-DD HH:mm:ss.SSS' format date string
utils.logDate(); // '2013-04-17 14:43:02.674'
utils.YYYYMMDDHHmmssSSS(); // '2013-04-17 14:43:02.674'
utils.YYYYMMDDHHmmssSSS(','); // '2013-04-17 14:43:02,674'

// 'YYYY-MM-DD HH:mm:ss' format date string
utils.YYYYMMDDHHmmss(); // '2013-04-17 14:43:02'
utils.YYYYMMDDHHmmss(new Date(), {dateSep: '.'}); // '2013.04.17 14:43:02'

// 'YYYY-MM-DD' format date string
utils.YYYYMMDD(); // '2013-04-17'
utils.YYYYMMDD(''); // '20130417'
utils.YYYYMMDD(','); // '2013,04,17'

// datestruct
utils.datestruct(); // { YYYYMMDD: 20130416, H: 8 }

// Unix's timestamp
utils.timestamp(); // 1378153226

// Parse timestamp
// seconds
utils.timestamp(1385091596); // Fri Nov 22 2013 11:39:56 GMT+0800 (CST)
// millseconds
utils.timestamp(1385091596000); // Fri Nov 22 2013 11:39:56 GMT+0800 (CST)

// Get Date from Milliseconds
utils.getDateFromMilliseconds(1385091596000) // 2013-11-22
utils.getDateFromMilliseconds(1385091596000, utility.DateFormat.DateTimeWithTimeZone) // 22/Nov/2013:01:46:36 +0000
utils.getDateFromMilliseconds(1385091596000, utility.DateFormat.DateTimeWithMilliSeconds) // 2013-11-22 01:46:36.000
utils.getDateFromMilliseconds(1385091596000, utility.DateFormat.DateTimeWithSeconds) // 2013-11-22 01:46:36
utils.getDateFromMilliseconds(1385091596000, utility.DateFormat.UnixTimestamp) // 1385091596

Number utils

// 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.

import { runWithTimeout } from 'utility';

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

map

Create a real map in javascript.

use Object.create(null)

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

// 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('<body> hi', '<body>', '$& body'); // '$& body hi'

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

Try

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 '

import { UNSTABLE_METHOD } from 'utility';

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

argumentsToArray

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

JSON

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

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

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

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

benchmark

$ node benchmark/date_format.cjs

moment().format("DD/MMM/YYYY:HH:mm:ss ZZ"): "16/Apr/2013:21:12:32 +0800"
utils.accessLogDate(): "16/Apr/2013:21:12:32 +0800"
fasterAccessDate(): "16/Apr/2013:21:12:32 +0800"
fasterAccessDate2(): "16/Apr/2013:21:12:32 +0800"
new Date().toString(): "Tue Apr 16 2013 21:12:32 GMT+0800 (CST)"
Date(): "Tue Apr 16 2013 21:12:32 GMT+0800 (CST)"
Date.now(): 1366117952162
------------------------
moment().format('DD/MMM/YYYY:HH:mm:ss ZZ') x 68,300 ops/sec ±5.05% (91 runs sampled)
utils.accessLogDate() x 1,341,341 ops/sec ±2.72% (90 runs sampled)
fasterAccessDate() x 357,833 ops/sec ±1.32% (98 runs sampled)
fasterAccessDate2() x 301,607 ops/sec ±5.03% (83 runs sampled)
new Date().toString() x 738,499 ops/sec ±3.54% (86 runs sampled)
Date() x 794,724 ops/sec ±2.77% (95 runs sampled)
Date.now() x 8,327,685 ops/sec ±1.85% (94 runs sampled)
Fastest is Date.now()

benchmark/date_YYYYMMDD.js

$ 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

Contributors

Made with contributors-img.

changelog (log de mudanças)

Changelog

2.5.0 (2025-01-14)

Features

  • support convert milliseconds and fix timezone (#66) (4bc6691)

2.4.0 (2024-12-22)

Features

  • support fs.exists async function (#65) (eb95f36)

2.3.0 (2024-12-18)

Features

2.2.0 (2024-12-10)

Features

2.1.0 (2024-03-13)

Features

2.0.0 (2024-01-13)

⚠ BREAKING CHANGES

  • drop Node.js < 16 support

Features

1.18.0 (2023-04-26)

Features


1.17.0 / 2020-12-15

features

others

1.16.3 / 2019-11-20

fixes

1.16.2 / 2019-11-19

fixes

others

1.16.1 / 2019-03-25

fixes

1.16.0 / 2019-03-25

features

1.15.1 / 2019-03-13

features

others

1.15.0 / 2018-09-12

features

others

1.14.0 / 2018-06-29

features

1.13.1 / 2017-10-17

fixes

1.13.0 / 2017-10-17

features

1.12.0 / 2017-04-19

  • feat: add includesInvalidHttpHeaderChar() to detect invalid char
  • test: add url test for replaceInvalidHttpHeaderChar
  • chore: remove unused comments
  • feat: replacement support function format

1.11.0 / 2017-02-21

  • feat: add utility.assign (#27)

1.10.0 / 2017-02-14

  • feat: add replace invalid http header character (#26)

1.9.0 / 2016-11-14

  • feat: add utils.random function (#25)
  • bench: add Array.from(arguments) bench test

1.8.0 / 2016-05-09

  • feat(array): impl faster splice one element on array (#24)

1.7.1 / 2016-05-03

  • refactor: use faster empty object instead of Object.create(null) (#23)

1.7.0 / 2016-04-07

  • benchmark: update arguments to array
  • chore: add doc
  • feat: add utility.argumentsToArray
  • chore: add david-dm status badge
  • deps: remove unuse mm module
  • test: use ava and nyc instead of mocha and istanbul
  • bench: add string and tpl string benchmark

1.6.0 / 2015-12-04

  • refactor: use escape-html

1.5.0 / 2015-11-25

  • feat: utility.dig
  • test(date): fix timezone on test assert
  • feat(date): make YYYYMMDDHHmmss() support param not Date
  • test: use codecov.io

1.4.0 / 2015-05-22

  • feat(JSON): add strict JSON parse

1.3.2 / 2015-05-08

  • feat(crypto): add sha256 hash

1.3.1 / 2015-04-09

  • fix(crypto): base64decode support return buffer

1.3.0 / 2015-01-31

  • feat(string): add string replace

1.2.1 / 2014-11-14

  • setImmediate support argmuents

1.2.0 / 2014-09-14

  • add utility.try

1.1.0 / 2014-08-23

  • add split(str, sep=,)

1.0.0 / 2014-08-01

  • remove address methods, please use address module

0.1.16 / 2014-07-07

  • fix deps

0.1.15 / 2014-07-07

  • YYYYMMDDHHmmss() support custom dateSep

0.1.14 / 2014-06-25

  • support YYYYMMDD(d, sep)
  • add YYYYMMDDHHmmss benchmark
  • add sha1 to readme
  • add random string benchmark

0.1.13 / 2014-04-24

  • utils.YYYYMMDDHHmmssSSS(','); // '2013-04-17 14:43:02,674'

0.1.12 / 2014-04-03

  • support var map = util.map({a: 1})

0.1.11 / 2014-03-15

  • add sha1()
  • remove config from scripts

0.1.10 / 2014-01-08

  • add randomString() and has() (@dead-horse)
  • install from cnpm

0.1.9 / 2013-12-09

  • add YYYYMMDD()

0.1.8 / 2013-11-25

  • support sub object md5

0.1.7 / 2013-11-23

  • support timestamp string

0.1.6 / 2013-11-23

  • parse timestamp

0.1.5 / 2013-11-23

  • hash object
  • add npm image

0.1.4 / 2013-11-16

  • utils.setImmediate()
  • fix test case

0.1.3 / 2013-10-23

  • add number utils: toSafeNumber()

0.1.2 / 2013-10-07

  • add utils.YYYYMMDDHHmmss()

0.1.1 / 2013-09-23

  • add base64 format md5

0.1.0 / 2013-09-03

  • add timestamp()

0.0.13 / 2013-07-31

  • move getIP() to address, fixed #2

0.0.12 / 2013-06-27

  • utils.getParamNames(): get a function parameters names

0.0.11 / 2013-06-25

  • fixed interface name wrong on liunx

0.0.10 / 2013-06-25

  • add getIP()
  • add more test cases

0.0.9 / 2013-05-08

  • Safe encodeURIComponent and decodeURIComponent

0.0.8 / 2013-05-06

  • add randomSlice() fixed #1

0.0.7 / 2013-04-17

  • fixed timezone +0000 and test cases

0.0.6 / 2013-04-17

  • utils.logDate(); // '2013-04-17 14:43:02.674'

0.0.5 / 2013-04-16

  • faster accesslogDate() impl
  • add benchmark

0.0.4 / 2013-04-16

  • add accessLogDate()

0.0.3 / 2013-03-06

  • add hmac()
  • update copyright year
  • update md5 readme

0.0.2 / 2013-01-31

  • add base64 encode and urlsafe base64 encode
  • add html escape()
  • update makefile

0.0.1 / 2012-11-13

  • first commit