{"name":"utility","version":"2.5.0","description":"A collection of useful utilities.","scripts":{"lint":"eslint src test --ext ts","pretest":"npm run lint -- --fix && npm run prepublishOnly","test":"egg-bin test","test-local":"egg-bin test","preci":"npm run lint && npm run prepublishOnly && attw --pack","ci":"egg-bin cov","prepublishOnly":"tshy && tshy-after"},"dependencies":{"escape-html":"^1.0.3","unescape":"^1.0.1","ylru":"^2.0.0"},"devDependencies":{"@arethetypeswrong/cli":"^0.17.1","@eggjs/tsconfig":"^1.3.3","@types/escape-html":"^1.0.4","@types/mocha":"^10.0.6","@types/node":"22","beautify-benchmark":"^0.2.4","benchmark":"^2.1.4","egg-bin":"^6.5.2","eslint":"^8.54.0","eslint-config-egg":"^13.0.0","moment":"^2.22.2","object-assign":"^4.1.1","optimized":"^1.2.0","time-require":"^0.1.2","tsd":"^0.28.1","tshy":"^3.0.2","tshy-after":"^1.0.0","typescript":"^5.2.2"},"homepage":"https://github.com/node-modules/utility","repository":{"type":"git","url":"git://github.com/node-modules/utility.git"},"keywords":["utility","util","utils","sha256","sha1","hash","hex"],"engines":{"node":">= 16.0.0"},"author":{"name":"fengmk2","email":"fengmk2@gmail.com","url":"https://github.com/fengmk2"},"license":"MIT","type":"module","tshy":{"exports":{"./package.json":"./package.json",".":"./src/index.ts"}},"exports":{"./package.json":"./package.json",".":{"import":{"types":"./dist/esm/index.d.ts","default":"./dist/esm/index.js"},"require":{"types":"./dist/commonjs/index.d.ts","default":"./dist/commonjs/index.js"}}},"main":"./dist/commonjs/index.js","types":"./dist/commonjs/index.d.ts","module":"./dist/esm/index.js","_id":"utility@2.5.0","gitHead":"62de14276c0da99a3bf23d5d0a80edc86b421a38","bugs":{"url":"https://github.com/node-modules/utility/issues"},"_nodeVersion":"18.20.5","_npmVersion":"10.8.2","dist":{"integrity":"sha512-lDbOVde5UAKgtxrSyZNhqrTA7f7anba6DTqbsDWgUFk6PZlmr7djqPYw0FnL5a6TbJvRt38VmYqt07zVLzXG2A==","shasum":"8fc8078d7d0bb35982db2eb95651632a7071bc5a","tarball":"http://registry-npm.ywwl.com/utility/download/utility-2.5.0.tgz","fileCount":71,"unpackedSize":189277,"attestations":{"url":"https://registry.npmjs.org/-/npm/v1/attestations/utility@2.5.0","provenance":{"predicateType":"https://slsa.dev/provenance/v1"}},"signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIAdxLJt0aSJHUE7vCe1DU9E9fMYl2uncc+Guj8hnY1e0AiEAwHqKXuL7KGcQy/X5EztOr9d9Oe00kHMs4YmiU++ZNgM="}],"size":36711,"noattachment":false,"key":"/utility/-/utility-2.5.0.tgz"},"_npmUser":{"name":"fengmk2","email":"fengmk2@gmail.com"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages-npm-production","tmp":"tmp/utility_2.5.0_1736818121344_0.7187749367178233"},"_hasShrinkwrap":false,"readme":"# utility\n\n[![NPM version][npm-image]][npm-url]\n[![CI](https://github.com/node-modules/utility/actions/workflows/nodejs.yml/badge.svg)](https://github.com/node-modules/utility/actions/workflows/nodejs.yml)\n[![Test coverage][codecov-image]][codecov-url]\n[![npm download][download-image]][download-url]\n[![Node.js Version](https://img.shields.io/node/v/utility.svg?style=flat)](https://nodejs.org/en/download/)\n[![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square)](https://makeapullrequest.com)\n\n[npm-image]: https://img.shields.io/npm/v/utility.svg?style=flat-square\n[npm-url]: https://npmjs.org/package/utility\n[codecov-image]: https://codecov.io/github/node-modules/utility/coverage.svg?branch=master\n[codecov-url]: https://codecov.io/github/node-modules/utility?branch=master\n[download-image]: https://img.shields.io/npm/dm/utility.svg?style=flat-square\n[download-url]: https://npmjs.org/package/utility\n\nA collection of useful utilities.\n\n## Install\n\n```bash\nnpm install utility\n```\n\n## Usage\n\n```js\nconst utils = require('utility');\n```\n\nAlso you can use it within typescript, like this ↓\n\n```ts\nimport * as utils from 'utility';\n```\n\n### md5\n\n```ts\nimport { md5 } from 'utility';\n\nmd5('苏千');\n// '5f733c47c58a077d61257102b2d44481'\n\nmd5(Buffer.from('苏千'));\n// '5f733c47c58a077d61257102b2d44481'\n\n// md5 base64 format\nmd5('苏千', 'base64'); \n// 'X3M8R8WKB31hJXECstREgQ=='\n\n// Object md5 hash. Sorted by key, and JSON.stringify. See source code for detail\nmd5({foo: 'bar', bar: 'foo'}).should.equal(md5({bar: 'foo', foo: 'bar'}));\n```\n\n### sha1\n\n```ts\nimport { sha1 } from 'utility';\n\nsha1('苏千');\n// '0a4aff6bab634b9c2f99b71f25e976921fcde5a5'\n\nsha1(Buffer.from('苏千'));\n// '0a4aff6bab634b9c2f99b71f25e976921fcde5a5'\n\n// sha1 base64 format\nsha1('苏千', 'base64');\n// 'Ckr/a6tjS5wvmbcfJel2kh/N5aU='\n\n// Object sha1 hash. Sorted by key, and JSON.stringify. See source code for detail\nsha1({foo: 'bar', bar: 'foo'}).should.equal(sha1({bar: 'foo', foo: 'bar'}));\n```\n\n### sha256\n\n```ts\nimport { sha256 } from 'utility';\n\nsha256(Buffer.from('苏千'));\n// '75dd03e3fcdbba7d5bec07900bae740cc8e361d77e7df8949de421d3df5d3635'\n```\n\n### hmac\n\n```ts\nimport { hmac } from 'utility';\n\n// hmac-sha1 with base64 output encoding\nhmac('sha1', 'I am a key', 'hello world');\n// 'pO6J0LKDxRRkvSECSEdxwKx84L0='\n```\n\n### decode and encode\n\n```ts\nimport { base64encode, base64decode, escape, unescape, encodeURIComponent, decodeURIComponent } from 'utility';\n\n// base64 encode\nbase64encode('你好￥');\n// '5L2g5aW977+l'\nbase64decode('5L2g5aW977+l');\n// '你好￥'\n\n// urlsafe base64 encode\nbase64encode('你好￥', true);\n// '5L2g5aW977-l'\nbase64decode('5L2g5aW977-l', true);\n// '你好￥'\n\n// html escape and unescape\nescape('<script/>\"& &amp;');\n// '&lt;script/&gt;&quot;&amp; &amp;amp;'\nunescape('&lt;script/&gt;&quot;&amp; &amp;amp;');\n// '<script/>\"& &amp;'\n\n// Safe encodeURIComponent and decodeURIComponent\ndecodeURIComponent(encodeURIComponent('你好, Node.js'));\n// '你好, Node.js'\n```\n\n### others\n\n___[WARNNING] `getIP()` remove, PLEASE use `https://github.com/node-modules/address` module instead.___\n\n```js\n// get a function parameter's names\nutils.getParamNames(function (key1, key2) {}); // ['key1', 'key2']\n\n// get a random string, default length is 16.\nutils.randomString(32, '1234567890'); //18774480824014856763726145106142\n\n// check if object has this property\nutils.has({hello: 'world'}, 'hello'); //true\n\n// empty function\nutils.noop = function () {}\n\n// throw out an assertion error if you were given an invalid \"func\"\ntry {\n  utils.getParamNames(null); // Only function is allowed\n} catch (err) {\n  console.error(err); // Assertion Error\n}\n```\n\n### Date utils\n\n```js\n// accessLogDate\nutils.accessLogDate(); // '16/Apr/2013:16:40:09 +0800'\n\n// logDate,\n// 'YYYY-MM-DD HH:mm:ss.SSS' format date string\nutils.logDate(); // '2013-04-17 14:43:02.674'\nutils.YYYYMMDDHHmmssSSS(); // '2013-04-17 14:43:02.674'\nutils.YYYYMMDDHHmmssSSS(','); // '2013-04-17 14:43:02,674'\n\n// 'YYYY-MM-DD HH:mm:ss' format date string\nutils.YYYYMMDDHHmmss(); // '2013-04-17 14:43:02'\nutils.YYYYMMDDHHmmss(new Date(), {dateSep: '.'}); // '2013.04.17 14:43:02'\n\n// 'YYYY-MM-DD' format date string\nutils.YYYYMMDD(); // '2013-04-17'\nutils.YYYYMMDD(''); // '20130417'\nutils.YYYYMMDD(','); // '2013,04,17'\n\n// datestruct\nutils.datestruct(); // { YYYYMMDD: 20130416, H: 8 }\n\n// Unix's timestamp\nutils.timestamp(); // 1378153226\n\n// Parse timestamp\n// seconds\nutils.timestamp(1385091596); // Fri Nov 22 2013 11:39:56 GMT+0800 (CST)\n// millseconds\nutils.timestamp(1385091596000); // Fri Nov 22 2013 11:39:56 GMT+0800 (CST)\n\n// Get Date from Milliseconds\nutils.getDateFromMilliseconds(1385091596000) // 2013-11-22\nutils.getDateFromMilliseconds(1385091596000, utility.DateFormat.DateTimeWithTimeZone) // 22/Nov/2013:01:46:36 +0000\nutils.getDateFromMilliseconds(1385091596000, utility.DateFormat.DateTimeWithMilliSeconds) // 2013-11-22 01:46:36.000\nutils.getDateFromMilliseconds(1385091596000, utility.DateFormat.DateTimeWithSeconds) // 2013-11-22 01:46:36\nutils.getDateFromMilliseconds(1385091596000, utility.DateFormat.UnixTimestamp) // 1385091596\n```\n\n### Number utils\n\n```js\n// Detect a number string can safe convert to Javascript Number.: `-9007199254740991 ~ 9007199254740991`\nutils.isSafeNumberString('9007199254740991'); // true\nutils.isSafeNumberString('9007199254740993'); // false\n\n// Convert string to number safe:\nutils.toSafeNumber('9007199254740991'); // 9007199254740991\nutils.toSafeNumber('9007199254740993'); // '9007199254740993'\n\n// Produces a random integer between the inclusive `lower` and exclusive `upper` bounds.\nutils.random(100); // [0, 100)\nutils.random(2, 1000); // [2, 1000)\nutils.random(); // 0\n```\n\n### Timeout\n\n#### `runWithTimeout(scope, timeout)`\n\nExecutes a scope promise with a specified timeout duration. If the promise doesn't resolve within the timeout period, it will reject with a `TimeoutError`.\n\n```ts\nimport { runWithTimeout } from 'utility';\n\nawait runWithTimeout(async () => {\n  // long run operation here\n}, 1000);\n```\n\n### map\n\nCreate a `real` map in javascript.\n\nuse `Object.create(null)`\n\n```js\nconst map = utils.map({a: 1});\n\n// should.not.exist(map.constructor);\n// should.not.exist(map.__proto__);\n// should.not.exist(map.toString);\n// should not exist any property\n\nconsole.log(map); // {a: 1}\n```\n\n### String utils\n\n```js\n// split string by sep\nutils.split('foo,bar,,,', ','); // ['foo', 'bar']\n\n// replace string work with special chars which `String.prototype.replace` can't handle\nutils.replace('<body> hi', '<body>', '$& body'); // '$& body hi'\n\n// replace http header invalid characters\nutils.replaceInvalidHttpHeaderChar('abc你好11'); // {invalid: true, val: 'abc  11'}\n```\n\n### Try\n\n```js\nconst res = utils.try(function () {\n  return JSON.parse(str);\n});\n\n// {error: undefined, value: {foo: 'bar'}}\n// {error: Error, value: undefined}\n```\n\n```Note``` that when you use ```typescript```, you must use the following methods to call ' Try '\n\n```js\nimport { UNSTABLE_METHOD } from 'utility';\n\nUNSTABLE_METHOD.try(...);\n...\n```\n\n### argumentsToArray\n\n```js\nfunction foo() {\n  const arr = utils.argumentsToArray(arguments);\n  console.log(arr.join(', '));\n}\n```\n\n### JSON\n\n```js\nconst obj = utils.strictJSONparse('\"hello\"');\n// will throw when JSON string is not object\n\nconst pkg = utils.readJSONSync('package.json');\nutils.writeJSONSync('package.json', pkg, {\n  replacer: null,\n  space: '\\t',\n});\n```\n\nOr you can use async API\n\n```js\nasync () => {\n  const pkg = await utils.readJSON('package.json');\n  await utils.writeJSON('package.json', pkg);\n}\n```\n\n> __Hint:__ In `utils.writeJSON*()`, if `pkg` is an object, the __optional__ third parameter `options` may contain two\n> keys.\n>\n> + `replacer`: Equals to `JSON.stringify()`'s second parameter;\n> + `space`: Equals to `JSON.stringify()`'s third parameter. Defaults to `2`.\n>\n> Refs:\n>\n> + <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#The_replacer_parameter>\n> + <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#The_space_argument>\n\n### Object.assign\n\n```js\n// assign object\nutils.assign({}, { a: 1 });\n\n// assign multiple object\nutils.assign({}, [ { a: 1 }, { b: 1 } ]);\n```\n\n## benchmark\n\n+ [jsperf: access log date format](http://jsperf.com/access-log-date-format)\n+ [benchmark/date_format.js](https://github.com/node-modules/utility/blob/master/benchmark/date_format.cjs)\n\n```bash\n$ node benchmark/date_format.cjs\n\nmoment().format(\"DD/MMM/YYYY:HH:mm:ss ZZ\"): \"16/Apr/2013:21:12:32 +0800\"\nutils.accessLogDate(): \"16/Apr/2013:21:12:32 +0800\"\nfasterAccessDate(): \"16/Apr/2013:21:12:32 +0800\"\nfasterAccessDate2(): \"16/Apr/2013:21:12:32 +0800\"\nnew Date().toString(): \"Tue Apr 16 2013 21:12:32 GMT+0800 (CST)\"\nDate(): \"Tue Apr 16 2013 21:12:32 GMT+0800 (CST)\"\nDate.now(): 1366117952162\n------------------------\nmoment().format('DD/MMM/YYYY:HH:mm:ss ZZ') x 68,300 ops/sec ±5.05% (91 runs sampled)\nutils.accessLogDate() x 1,341,341 ops/sec ±2.72% (90 runs sampled)\nfasterAccessDate() x 357,833 ops/sec ±1.32% (98 runs sampled)\nfasterAccessDate2() x 301,607 ops/sec ±5.03% (83 runs sampled)\nnew Date().toString() x 738,499 ops/sec ±3.54% (86 runs sampled)\nDate() x 794,724 ops/sec ±2.77% (95 runs sampled)\nDate.now() x 8,327,685 ops/sec ±1.85% (94 runs sampled)\nFastest is Date.now()\n```\n\n[benchmark/date_YYYYMMDD.js](https://github.com/node-modules/utility/blob/master/benchmark/date_YYYYMMDD.cjs)\n\n```bash\n$ node benchmark/date_YYYYMMDD.cjs\n\nparseInt(moment().format(\"YYYYMMDD\"), 10): 20130416\nutils.datestruct().YYYYMMDD: 20130416\nnew Date().toString(): \"Tue Apr 16 2013 21:12:02 GMT+0800 (CST)\"\n------------------------\nparseInt(moment().format('YYYYMMDD'), 10) x 129,604 ops/sec ±0.46% (101 runs sampled)\nutils.datestruct().YYYYMMDD x 2,317,461 ops/sec ±1.38% (95 runs sampled)\nnew Date().toString() x 816,731 ops/sec ±3.46% (93 runs sampled)\nFastest is utils.datestruct().YYYYMMDD\n```\n\n## License\n\n[MIT](LICENSE.txt)\n\n## Contributors\n\n[![Contributors](https://contrib.rocks/image?repo=node-modules/utility)](https://github.com/node-modules/utility/graphs/contributors)\n\nMade with [contributors-img](https://contrib.rocks).\n","publish_time":1736818121567,"maintainers":[{"name":"dead_horse","email":"dead_horse@qq.com"},{"name":"xadillax","email":"admin@xcoder.in"},{"name":"fengmk2","email":"fengmk2@gmail.com"}],"_cnpm_publish_time":1736818121567,"dist-tags":{"latest":"2.5.1"}}