Gathering detailed insights and metrics for utility
Gathering detailed insights and metrics for utility
npm install utility
Typescript
Module System
Min. Node Version
Node Version
NPM Version
99.2
Supply Chain
99.6
Quality
89.4
Maintenance
100
Vulnerability
100
License
TypeScript (65.33%)
JavaScript (34.67%)
Love this project? Help keep it running — sponsor us today! 🚀
Total Downloads
77,549,278
Last Day
1,610
Last Week
1,610
Last Month
861,178
Last Year
14,179,133
1,241 Stars
199 Commits
161 Forks
71 Watching
1 Branches
30 Contributors
Minified
Minified + Gzipped
Latest Version
2.5.0
Package Id
utility@2.5.0
Unpacked Size
184.84 kB
Size
35.85 kB
File Count
71
NPM Version
10.8.2
Node Version
18.20.5
Publised On
14 Jan 2025
Cumulative downloads
Total Downloads
Last day
0%
1,610
Compared to previous day
Last week
-99.1%
1,610
Compared to previous week
Last month
-26.9%
861,178
Compared to previous month
Last year
-16.4%
14,179,133
Compared to previous year
A collection of useful utilities.
1npm install utility
1const utils = require('utility');
Also you can use it within typescript, like this ↓
1import * as utils from 'utility';
1import { md5 } from 'utility'; 2 3md5('苏千'); 4// '5f733c47c58a077d61257102b2d44481' 5 6md5(Buffer.from('苏千')); 7// '5f733c47c58a077d61257102b2d44481' 8 9// md5 base64 format 10md5('苏千', 'base64'); 11// 'X3M8R8WKB31hJXECstREgQ==' 12 13// Object md5 hash. Sorted by key, and JSON.stringify. See source code for detail 14md5({foo: 'bar', bar: 'foo'}).should.equal(md5({bar: 'foo', foo: 'bar'}));
1import { sha1 } from 'utility'; 2 3sha1('苏千'); 4// '0a4aff6bab634b9c2f99b71f25e976921fcde5a5' 5 6sha1(Buffer.from('苏千')); 7// '0a4aff6bab634b9c2f99b71f25e976921fcde5a5' 8 9// sha1 base64 format 10sha1('苏千', 'base64'); 11// 'Ckr/a6tjS5wvmbcfJel2kh/N5aU=' 12 13// Object sha1 hash. Sorted by key, and JSON.stringify. See source code for detail 14sha1({foo: 'bar', bar: 'foo'}).should.equal(sha1({bar: 'foo', foo: 'bar'}));
1import { sha256 } from 'utility'; 2 3sha256(Buffer.from('苏千')); 4// '75dd03e3fcdbba7d5bec07900bae740cc8e361d77e7df8949de421d3df5d3635'
1import { hmac } from 'utility'; 2 3// hmac-sha1 with base64 output encoding 4hmac('sha1', 'I am a key', 'hello world'); 5// 'pO6J0LKDxRRkvSECSEdxwKx84L0='
1import { base64encode, base64decode, escape, unescape, encodeURIComponent, decodeURIComponent } from 'utility'; 2 3// base64 encode 4base64encode('你好¥'); 5// '5L2g5aW977+l' 6base64decode('5L2g5aW977+l'); 7// '你好¥' 8 9// urlsafe base64 encode 10base64encode('你好¥', true); 11// '5L2g5aW977-l' 12base64decode('5L2g5aW977-l', true); 13// '你好¥' 14 15// html escape and unescape 16escape('<script/>"& &'); 17// '<script/>"& &amp;' 18unescape('<script/>"& &amp;'); 19// '<script/>"& &' 20 21// Safe encodeURIComponent and decodeURIComponent 22decodeURIComponent(encodeURIComponent('你好, Node.js')); 23// '你好, Node.js'
[WARNNING] getIP()
remove, PLEASE use https://github.com/node-modules/address
module instead.
1// get a function parameter's names 2utils.getParamNames(function (key1, key2) {}); // ['key1', 'key2'] 3 4// get a random string, default length is 16. 5utils.randomString(32, '1234567890'); //18774480824014856763726145106142 6 7// check if object has this property 8utils.has({hello: 'world'}, 'hello'); //true 9 10// empty function 11utils.noop = function () {} 12 13// throw out an assertion error if you were given an invalid "func" 14try { 15 utils.getParamNames(null); // Only function is allowed 16} catch (err) { 17 console.error(err); // Assertion Error 18}
1// accessLogDate 2utils.accessLogDate(); // '16/Apr/2013:16:40:09 +0800' 3 4// logDate, 5// 'YYYY-MM-DD HH:mm:ss.SSS' format date string 6utils.logDate(); // '2013-04-17 14:43:02.674' 7utils.YYYYMMDDHHmmssSSS(); // '2013-04-17 14:43:02.674' 8utils.YYYYMMDDHHmmssSSS(','); // '2013-04-17 14:43:02,674' 9 10// 'YYYY-MM-DD HH:mm:ss' format date string 11utils.YYYYMMDDHHmmss(); // '2013-04-17 14:43:02' 12utils.YYYYMMDDHHmmss(new Date(), {dateSep: '.'}); // '2013.04.17 14:43:02' 13 14// 'YYYY-MM-DD' format date string 15utils.YYYYMMDD(); // '2013-04-17' 16utils.YYYYMMDD(''); // '20130417' 17utils.YYYYMMDD(','); // '2013,04,17' 18 19// datestruct 20utils.datestruct(); // { YYYYMMDD: 20130416, H: 8 } 21 22// Unix's timestamp 23utils.timestamp(); // 1378153226 24 25// Parse timestamp 26// seconds 27utils.timestamp(1385091596); // Fri Nov 22 2013 11:39:56 GMT+0800 (CST) 28// millseconds 29utils.timestamp(1385091596000); // Fri Nov 22 2013 11:39:56 GMT+0800 (CST) 30 31// Get Date from Milliseconds 32utils.getDateFromMilliseconds(1385091596000) // 2013-11-22 33utils.getDateFromMilliseconds(1385091596000, utility.DateFormat.DateTimeWithTimeZone) // 22/Nov/2013:01:46:36 +0000 34utils.getDateFromMilliseconds(1385091596000, utility.DateFormat.DateTimeWithMilliSeconds) // 2013-11-22 01:46:36.000 35utils.getDateFromMilliseconds(1385091596000, utility.DateFormat.DateTimeWithSeconds) // 2013-11-22 01:46:36 36utils.getDateFromMilliseconds(1385091596000, utility.DateFormat.UnixTimestamp) // 1385091596
1// Detect a number string can safe convert to Javascript Number.: `-9007199254740991 ~ 9007199254740991` 2utils.isSafeNumberString('9007199254740991'); // true 3utils.isSafeNumberString('9007199254740993'); // false 4 5// Convert string to number safe: 6utils.toSafeNumber('9007199254740991'); // 9007199254740991 7utils.toSafeNumber('9007199254740993'); // '9007199254740993' 8 9// Produces a random integer between the inclusive `lower` and exclusive `upper` bounds. 10utils.random(100); // [0, 100) 11utils.random(2, 1000); // [2, 1000) 12utils.random(); // 0
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
.
1import { runWithTimeout } from 'utility'; 2 3await runWithTimeout(async () => { 4 // long run operation here 5}, 1000);
Create a real
map in javascript.
use Object.create(null)
1const map = utils.map({a: 1}); 2 3// should.not.exist(map.constructor); 4// should.not.exist(map.__proto__); 5// should.not.exist(map.toString); 6// should not exist any property 7 8console.log(map); // {a: 1}
1// split string by sep 2utils.split('foo,bar,,,', ','); // ['foo', 'bar'] 3 4// replace string work with special chars which `String.prototype.replace` can't handle 5utils.replace('<body> hi', '<body>', '$& body'); // '$& body hi' 6 7// replace http header invalid characters 8utils.replaceInvalidHttpHeaderChar('abc你好11'); // {invalid: true, val: 'abc 11'}
1const res = utils.try(function () { 2 return JSON.parse(str); 3}); 4 5// {error: undefined, value: {foo: 'bar'}} 6// {error: Error, value: undefined}
Note
that when you use typescript
, you must use the following methods to call ' Try '
1import { UNSTABLE_METHOD } from 'utility'; 2 3UNSTABLE_METHOD.try(...); 4...
1function foo() { 2 const arr = utils.argumentsToArray(arguments); 3 console.log(arr.join(', ')); 4}
1const obj = utils.strictJSONparse('"hello"');
2// will throw when JSON string is not object
3
4const pkg = utils.readJSONSync('package.json');
5utils.writeJSONSync('package.json', pkg, {
6 replacer: null,
7 space: '\t',
8});
Or you can use async API
1async () => {
2 const pkg = await utils.readJSON('package.json');
3 await utils.writeJSON('package.json', pkg);
4}
Hint: In
utils.writeJSON*()
, ifpkg
is an object, the optional third parameteroptions
may contain two keys.
replacer
: Equals toJSON.stringify()
's second parameter;space
: Equals toJSON.stringify()
's third parameter. Defaults to2
.Refs:
1// assign object 2utils.assign({}, { a: 1 }); 3 4// assign multiple object 5utils.assign({}, [ { a: 1 }, { b: 1 } ]);
1$ node benchmark/date_format.cjs 2 3moment().format("DD/MMM/YYYY:HH:mm:ss ZZ"): "16/Apr/2013:21:12:32 +0800" 4utils.accessLogDate(): "16/Apr/2013:21:12:32 +0800" 5fasterAccessDate(): "16/Apr/2013:21:12:32 +0800" 6fasterAccessDate2(): "16/Apr/2013:21:12:32 +0800" 7new Date().toString(): "Tue Apr 16 2013 21:12:32 GMT+0800 (CST)" 8Date(): "Tue Apr 16 2013 21:12:32 GMT+0800 (CST)" 9Date.now(): 1366117952162 10------------------------ 11moment().format('DD/MMM/YYYY:HH:mm:ss ZZ') x 68,300 ops/sec ±5.05% (91 runs sampled) 12utils.accessLogDate() x 1,341,341 ops/sec ±2.72% (90 runs sampled) 13fasterAccessDate() x 357,833 ops/sec ±1.32% (98 runs sampled) 14fasterAccessDate2() x 301,607 ops/sec ±5.03% (83 runs sampled) 15new Date().toString() x 738,499 ops/sec ±3.54% (86 runs sampled) 16Date() x 794,724 ops/sec ±2.77% (95 runs sampled) 17Date.now() x 8,327,685 ops/sec ±1.85% (94 runs sampled) 18Fastest is Date.now()
1$ node benchmark/date_YYYYMMDD.cjs 2 3parseInt(moment().format("YYYYMMDD"), 10): 20130416 4utils.datestruct().YYYYMMDD: 20130416 5new Date().toString(): "Tue Apr 16 2013 21:12:02 GMT+0800 (CST)" 6------------------------ 7parseInt(moment().format('YYYYMMDD'), 10) x 129,604 ops/sec ±0.46% (101 runs sampled) 8utils.datestruct().YYYYMMDD x 2,317,461 ops/sec ±1.38% (95 runs sampled) 9new Date().toString() x 816,731 ops/sec ±3.46% (93 runs sampled) 10Fastest is utils.datestruct().YYYYMMDD
Made with contributors-img.
No vulnerabilities found.
Reason
no dangerous workflow patterns detected
Reason
no binaries found in the repo
Reason
0 existing vulnerabilities detected
Reason
license file detected
Details
Reason
8 commit(s) and 2 issue activity found in the last 90 days -- score normalized to 8
Reason
SAST tool is not run on all commits -- score normalized to 3
Details
Reason
Found 5/30 approved changesets -- score normalized to 1
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
project is not fuzzed
Details
Reason
security policy file not detected
Details
Score
Last Scanned on 2025-01-27
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More