function YYYYMMDD(d, sep) { if (typeof d === 'string') { // YYYYMMDD(sep) sep = d; d = new Date(); } else { // YYYYMMDD(d, sep) d = d || new Date(); if (typeof sep !== 'string') { sep = '-'; } } var date = d.getDate(); if (date < 10) { date = '0' + date; } var month = d.getMonth() + 1; if (month < 10) { month = '0' + month; } return d.getFullYear() + sep + month + sep + date; }
...
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
...
YYYYMMDDHHmmss = function (d, options) { d = d || new Date(); if (!(d instanceof Date)) { d = new Date(d); } var dateSep = '-'; var timeSep = ':'; if (options) { if (options.dateSep) { dateSep = options.dateSep; } if (options.timeSep) { timeSep = options.timeSep; } } var date = d.getDate(); if (date < 10) { date = '0' + date; } var month = d.getMonth() + 1; if (month < 10) { month = '0' + month; } var hours = d.getHours(); if (hours < 10) { hours = '0' + hours; } var mintues = d.getMinutes(); if (mintues < 10) { mintues = '0' + mintues; } var seconds = d.getSeconds(); if (seconds < 10) { seconds = '0' + seconds; } return d.getFullYear() + dateSep + month + dateSep + date + ' ' + hours + timeSep + mintues + timeSep + seconds; }
...
// 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'
...
YYYYMMDDHHmmssSSS = function (d, msSep) { if (typeof d === 'string') { // logDate(msSep) msSep = d; d = new Date(); } else { // logDate(d, msSep) d = d || new Date(); } var date = d.getDate(); if (date < 10) { date = '0' + date; } var month = d.getMonth() + 1; if (month < 10) { month = '0' + month; } var hours = d.getHours(); if (hours < 10) { hours = '0' + hours; } var mintues = d.getMinutes(); if (mintues < 10) { mintues = '0' + mintues; } var seconds = d.getSeconds(); if (seconds < 10) { seconds = '0' + seconds; } var milliseconds = d.getMilliseconds(); if (milliseconds < 10) { milliseconds = '00' + milliseconds; } else if (milliseconds < 100) { milliseconds = '0' + milliseconds; } return d.getFullYear() + '-' + month + '-' + date + ' ' + hours + ':' + mintues + ':' + seconds + (msSep || '.') + milliseconds; }
...
```js
// 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
...
accessLogDate = function (d) { // 16/Apr/2013:16:40:09 +0800 d = d || new Date(); var date = d.getDate(); if (date < 10) { date = '0' + date; } var hours = d.getHours(); if (hours < 10) { hours = '0' + hours; } var mintues = d.getMinutes(); if (mintues < 10) { mintues = '0' + mintues; } var seconds = d.getSeconds(); if (seconds < 10) { seconds = '0' + seconds; } return date + '/' + MONTHS[d.getMonth()] + '/' + d.getFullYear() + ':' + hours + ':' + mintues + ':' + seconds + TIMEZONE; }
...
}
```
### Date utils
```js
// 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'
...
argumentsToArray = function (args) { var res = new Array(args.length); for (var i = 0; i < args.length; i++) { res[i] = args[i]; } return res; }
...
// {error: Error, value: undefined}
```
### argumentsToArray
```js
function() {
const arr = utility.argumentsToArray(arguments);
console.log(arr.join(', '));
}
```
### JSON
```js
...
assign = function (target, objects) { if (!Array.isArray(objects)) { objects = [ objects ]; } for (var i = 0; i < objects.length; i++) { var obj = objects[i]; if (obj) { var keys = Object.keys(obj); for (var j = 0; j < keys.length; j++) { var key = keys[j]; target[key] = obj[key]; } } } return target; }
...
```
### Object.assign
```js
// assign object
utility.assign({}, { a: 1 });
// assign multiple object
utility.assign({}, [ { a: 1 }, { b: 1 } ]);
```
## benchmark
...
function base64decode(encodeStr, urlsafe, encoding) { if (urlsafe) { encodeStr = encodeStr.replace(/\-/g, '+').replace(/_/g, '/'); } var buf = new Buffer(encodeStr, 'base64'); if (encoding === 'buffer') { return buf; } return buf.toString(encoding || 'utf8'); }
...
```
### decode and encode
```js
// base64 encode
utils.base64encode('你好¥'); // '5L2g5aW977+l'
utils.base64decode('5L2g5aW977+l') // '你好¥'
// urlsafe base64 encode
utils.base64encode('你好¥', true); // '5L2g5aW977-l'
utils.base64decode('5L2g5aW977-l', true); // '你好¥'
// html escape
utils.escape('<script/>"& &'); // '<script/>"&
x26;amp;'
...
function base64encode(s, urlsafe) { if (!Buffer.isBuffer(s)) { s = new Buffer(s); } var encode = s.toString('base64'); if (urlsafe) { encode = encode.replace(/\+/g, '-').replace(/\//g, '_'); } return encode; }
...
utils.hmac('sha1', 'I am a key', 'hello world'); // 'pO6J0LKDxRRkvSECSEdxwKx84L0='
```
### decode and encode
```js
// base64 encode
utils.base64encode('你好¥'); // '5L2g5aW977+l'
utils.base64decode('5L2g5aW977+l') // '你好¥'
// urlsafe base64 encode
utils.base64encode('你好¥', true); // '5L2g5aW977-l'
utils.base64decode('5L2g5aW977-l', true); // '你好¥'
// html escape
...
datestruct = function (now) { now = now || new Date(); return { YYYYMMDD: now.getFullYear() * 10000 + (now.getMonth() + 1) * 100 + now.getDate(), H: now.getHours() }; }
...
// '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)
...
function decodeURIComponent_(encodeText) { try { return decodeURIComponent(encodeText); } catch (e) { return encodeText; } }
...
utils.base64encode('你好¥', true); // '5L2g5aW977-l'
utils.base64decode('5L2g5aW977-l', true); // '你好¥'
// html escape
utils.escape('<script/>"& &'); // '<script/>"&
x26;amp;'
// Safe encodeURIComponent and decodeURIComponent
utils.decodeURIComponent(utils.encodeURIComponent('你好, nodejs')).should.equal
('你好, nodejs');
```
### others
___[WARNNING] getIP() remove, PLEASE use `https://github.com/node-modules/address` module instead.___
```js
...
dig = function (obj) { if (!obj) { return; } if (arguments.length <= 1) { return obj; } var value = obj[arguments[1]]; for (var i = 2; i < arguments.length; i++) { if (!value) { break; } value = value[arguments[i]]; } return value; }
n/a
function encodeURIComponent_(text) { try { return encodeURIComponent(text); } catch (e) { return text; } }
...
utils.base64encode('你好¥', true); // '5L2g5aW977-l'
utils.base64decode('5L2g5aW977-l', true); // '你好¥'
// html escape
utils.escape('<script/>"& &'); // '<script/>"&
x26;amp;'
// Safe encodeURIComponent and decodeURIComponent
utils.decodeURIComponent(utils.encodeURIComponent('你好, nodejs')).should.equal
('你好, nodejs');
```
### others
___[WARNNING] getIP() remove, PLEASE use `https://github.com/node-modules/address` module instead.___
```js
...
function escapeHtml(string) { var str = '' + string; var match = matchHtmlRegExp.exec(str); if (!match) { return str; } var escape; var html = ''; var index = 0; var lastIndex = 0; for (index = match.index; index < str.length; index++) { switch (str.charCodeAt(index)) { case 34: // " escape = '"'; break; case 38: // & escape = '&'; break; case 39: // ' escape = '''; break; case 60: // < escape = '<'; break; case 62: // > escape = '>'; break; default: continue; } if (lastIndex !== index) { html += str.substring(lastIndex, index); } lastIndex = index + 1; html += escape; } return lastIndex !== index ? html + str.substring(lastIndex, index) : html; }
...
utils.base64decode('5L2g5aW977+l') // '你好¥'
// urlsafe base64 encode
utils.base64encode('你好¥', true); // '5L2g5aW977-l'
utils.base64decode('5L2g5aW977-l', true); // '你好¥'
// html escape
utils.escape('<script/>"& &'); // '&
lt;script/>"& &'
// Safe encodeURIComponent and decodeURIComponent
utils.decodeURIComponent(utils.encodeURIComponent('你好, nodejs')).should.equal('你好, nodejs');
```
### others
...
function getParamNames(func, cache) { cache = cache !== false; if (cache && func.__cache_names) { return func.__cache_names; } var str = func.toString(); var names = str.slice(str.indexOf('(') + 1, str.indexOf(')')).match(/([^\s,]+)/g) || []; func.__cache_names = names; return names; }
...
### others
___[WARNNING] getIP() remove, PLEASE use `https://github.com/node-modules/address` module instead.___
```js
// 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
...
function has(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); }
...
// 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 () {}
}
```
### Date utils
...
function hash(method, s, format) { var sum = crypto.createHash(method); var isBuffer = Buffer.isBuffer(s); if (!isBuffer && typeof s === 'object') { s = JSON.stringify(sortObject(s)); } sum.update(s, isBuffer ? 'binary' : 'utf8'); return sum.digest(format || 'hex'); }
...
*
* @param {String|Buffer} s
* @param {String} [format] output string format, could be 'hex' or 'base64'. default is 'hex'.
* @return {String} md5 hash string
* @public
*/
exports.md5 = function md5(s, format) {
return exports.hash('md5', s, format);
};
/**
* sha1 hash
*
* @param {String|Buffer} s
* @param {String} [format] output string format, could be 'hex' or 'base64'. default is 'hex'.
...
function hmac(algorithm, key, data, encoding) { encoding = encoding || 'base64'; var hmac = crypto.createHmac(algorithm, key); hmac.update(data, Buffer.isBuffer(data) ? 'binary' : 'utf8'); return hmac.digest(encoding); }
...
utils.sha256(new Buffer('苏千')).should.equal('75dd03e3fcdbba7d5bec07900bae740cc8e361d77e7df8949de421d3df5d3635'
;);
```
### hmac
```js
// hmac-sha1 with base64 output encoding
utils.hmac('sha1', 'I am a key', 'hello world'); // '
;pO6J0LKDxRRkvSECSEdxwKx84L0='
```
### decode and encode
```js
// base64 encode
utils.base64encode('你好¥'); // '5L2g5aW977+l'
...
function includesInvalidHttpHeaderChar(val) { if (!val || typeof val !== 'string') { return false; } for (var i = 0; i < val.length; ++i) { if (!validHdrChars[val.charCodeAt(i)]) { return true; } } return false; }
n/a
function isSafeNumberString(s) { if (s[0] === '-') { s = s.substring(1); } if (s.length < MAX_SAFE_INTEGER_STR_LENGTH || (s.length === MAX_SAFE_INTEGER_STR_LENGTH && s <= MAX_SAFE_INTEGER_STR)) { return true; } return false; }
...
utils.timestamp(1385091596000); // Fri Nov 22 2013 11:39:56 GMT+0800 (CST)
```
### Number utils
```js
// 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.
...
logDate = function (d, msSep) { if (typeof d === 'string') { // logDate(msSep) msSep = d; d = new Date(); } else { // logDate(d, msSep) d = d || new Date(); } var date = d.getDate(); if (date < 10) { date = '0' + date; } var month = d.getMonth() + 1; if (month < 10) { month = '0' + month; } var hours = d.getHours(); if (hours < 10) { hours = '0' + hours; } var mintues = d.getMinutes(); if (mintues < 10) { mintues = '0' + mintues; } var seconds = d.getSeconds(); if (seconds < 10) { seconds = '0' + seconds; } var milliseconds = d.getMilliseconds(); if (milliseconds < 10) { milliseconds = '00' + milliseconds; } else if (milliseconds < 100) { milliseconds = '0' + milliseconds; } return d.getFullYear() + '-' + month + '-' + date + ' ' + hours + ':' + mintues + ':' + seconds + (msSep || '.') + milliseconds; }
...
```js
// 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'
...
function map(obj) { var map = new EmptyObject(); if (!obj) { return map; } for (var key in obj) { map[key] = obj[key]; } return map; }
...
### map
Create a `real` map in javascript.
use `Object.create(null)`
```js
const map = utils.map({a: 1});
// should.not.exist(map.constractor);
// should.not.exist(map.__proto__);
// should.not.exist(map.toString);
// should not exist any property
console.log(map); // {a: 1}
...
function md5(s, format) { return exports.hash('md5', s, format); }
...
```js
const utils = require('utility');
```
### md5
```js
utils.md5('苏千').should.equal('5f733c47c58a077d61257102b2d44481');
utils.md5(new Buffer('苏千')).should.equal('5f733c47c58a077d61257102b2d44481');
// md5 base64 format
utils.md5('苏千', 'base64'); // 'X3M8R8WKB31hJXECstREgQ=='
// Object md5 hash. Sorted by key, and JSON.stringify. See source code for detail
utils.md5({foo: 'bar', bar: 'foo'}).should.equal(utils.md5({bar: 'foo', foo: 'bar'}));
```
...
function noop() {}
n/a
function random(lower, upper) { if (lower === undefined && upper === undefined) { return 0; } if (upper === undefined) { upper = lower; lower = 0; } var temp; if (lower > upper) { temp = lower; lower = upper; upper = temp; } return Math.floor(lower + Math.random() * (upper - lower)); }
...
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
```
### Timers
```js
...
function randomSlice(arr, num) { if (!num || num >= arr.length) { return arr.slice(); } var index = Math.floor(Math.random() * arr.length); var a = []; for (var i = 0, j = index; i < num; i++) { a.push(arr[j++]); if (j === arr.length) { j = 0; } } return a; }
n/a
function randomString(length, charSet) { var result = []; length = length || 16; charSet = charSet || 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; while (length--) { result.push(charSet[Math.floor(Math.random() * charSet.length)]); } return result.join(''); }
...
___[WARNNING] getIP() remove, PLEASE use `https://github.com/node-modules/address` module instead.___
```js
// 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 () {}
}
...
function replace(str, substr, newSubstr) { var replaceFunction = newSubstr; if (typeof replaceFunction !== 'function') { replaceFunction = function () { return newSubstr; }; } return str.replace(substr, replaceFunction); }
...
### String utils
```js
// 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>', '$
x26; body'); // '$& body hi'
// replace http header invalid characters
utils.replaceInvalidHttpHeaderChar('abc你好11'); // {invalid: true, val: 'abc 11'}
```
### Try
...
function replaceInvalidHttpHeaderChar(val, replacement) { replacement = replacement || ' '; var invalid = false; if (!val || typeof val !== 'string') { return { val: val, invalid: invalid, }; } var replacementType = typeof replacement; var chars; for (var i = 0; i < val.length; ++i) { if (!validHdrChars[val.charCodeAt(i)]) { // delay create chars chars = chars || val.split(''); if (replacementType === 'function') { chars[i] = replacement(chars[i]); } else { chars[i] = replacement; } } } if (chars) { val = chars.join(''); invalid = true; } return { val: val, invalid: invalid, }; }
...
// 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
```js
const res = utils.try(function () {
return JSON.parse(str);
...
setImmediate = function () {
/*
* this function will do nothing
*/
return;
}
...
utils.random(2, 1000); // [2, 1000)
utils.random(); // 0
```
### Timers
```js
utils.setImmediate(function () {
console.log('hi');
});
```
### map
Create a `real` map in javascript.
...
function sha1(s, format) { return exports.hash('sha1', s, format); }
...
// Object md5 hash. Sorted by key, and JSON.stringify. See source code for detail
utils.md5({foo: 'bar', bar: 'foo'}).should.equal(utils.md5({bar: 'foo', foo: 'bar'}));
```
### sha1
```js
utils.sha1('苏千').should.equal('0a4aff6bab634b9c2f99b71f25e976921fcde5a5
');
utils.sha1(new Buffer('苏千')).should.equal('0a4aff6bab634b9c2f99b71f25e976921fcde5a5');
// sha1 base64 format
utils.sha1('苏千', 'base64'); // 'Ckr/a6tjS5wvmbcfJel2kh/N5aU='
// Object sha1 hash. Sorted by key, and JSON.stringify. See source code for detail
utils.sha1({foo: 'bar', bar: 'foo'}).should.equal(utils.sha1({bar: 'foo', foo: 'bar'}));
```
...
function sha1(s, format) { return exports.hash('sha256', s, format); }
...
// Object sha1 hash. Sorted by key, and JSON.stringify. See source code for detail
utils.sha1({foo: 'bar', bar: 'foo'}).should.equal(utils.sha1({bar: 'foo', foo: 'bar'}));
```
### sha256
```js
utils.sha256(new Buffer('苏千')).should.equal('75dd03e3fcdbba7d5bec07900bae740cc8e361d77e7df8949de421d3df5d3635
');
```
### hmac
```js
// hmac-sha1 with base64 output encoding
utils.hmac('sha1', 'I am a key', 'hello world'); // 'pO6J0LKDxRRkvSECSEdxwKx84L0='
...
function spliceOne(arr, index) { if (index < 0) { index = arr.length + index; // still negative, not found element if (index < 0) { return arr; } } // don't touch if (index >= arr.length) { return arr; } for (var i = index, k = i + 1, n = arr.length; k < n; i += 1, k += 1) { arr[i] = arr[k]; } arr.pop(); return arr; }
n/a
function split(str, sep) { str = str || ''; sep = sep || ','; var items = str.split(sep); var needs = []; for (var i = 0; i < items.length; i++) { var s = items[i].trim(); if (s.length > 0) { needs.push(s); } } return needs; }
...
console.log(map); // {a: 1}
```
### String utils
```js
// 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'}
```
...
function splitAlwaysOptimized() { var str = ''; var sep = ','; if (arguments.length === 1) { str = arguments[0] || ''; } else if (arguments.length === 2) { str = arguments[0] || ''; sep = arguments[1] || ','; } var items = str.split(sep); var needs = []; for (var i = 0; i < items.length; i++) { var s = items[i].trim(); if (s.length > 0) { needs.push(s); } } return needs; }
n/a
strictJSONParse = function (str) { var obj = JSON.parse(str); if (!obj || typeof obj !== 'object') { throw new Error('JSON string is not object'); } return obj; }
n/a
function timestamp(t) { if (t) { var v = t; if (typeof v === 'string') { v = Number(v); } if (String(t).length === 10) { v *= 1000; } return new Date(v); } return Math.round(Date.now() / 1000); }
...
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)
```
...
function toSafeNumber(s) { if (typeof s === 'number') { return s; } return exports.isSafeNumberString(s) ? Number(s) : s; }
...
```js
// 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
```
...
try = function (fn) { var res = { error: undefined, value: undefined }; try { res.value = fn(); } catch (err) { res.error = err instanceof Error ? err : new Error(err); } return res; }
...
// replace http header invalid characters
utils.replaceInvalidHttpHeaderChar('abc你好11'); // {invalid: true, val: 'abc 11'}
```
### Try
```js
const res = utils.try(function () {
return JSON.parse(str);
});
// {error: undefined, value: {foo: 'bar'}}
// {error: Error, value: undefined}
```
...
function randomSlice(arr, num) { if (!num || num >= arr.length) { return arr.slice(); } var index = Math.floor(Math.random() * arr.length); var a = []; for (var i = 0, j = index; i < num; i++) { a.push(arr[j++]); if (j === arr.length) { j = 0; } } return a; }
n/a
function spliceOne(arr, index) { if (index < 0) { index = arr.length + index; // still negative, not found element if (index < 0) { return arr; } } // don't touch if (index >= arr.length) { return arr; } for (var i = index, k = i + 1, n = arr.length; k < n; i += 1, k += 1) { arr[i] = arr[k]; } arr.pop(); return arr; }
n/a
function base64decode(encodeStr, urlsafe, encoding) { if (urlsafe) { encodeStr = encodeStr.replace(/\-/g, '+').replace(/_/g, '/'); } var buf = new Buffer(encodeStr, 'base64'); if (encoding === 'buffer') { return buf; } return buf.toString(encoding || 'utf8'); }
...
```
### decode and encode
```js
// base64 encode
utils.base64encode('你好¥'); // '5L2g5aW977+l'
utils.base64decode('5L2g5aW977+l') // '你好¥'
// urlsafe base64 encode
utils.base64encode('你好¥', true); // '5L2g5aW977-l'
utils.base64decode('5L2g5aW977-l', true); // '你好¥'
// html escape
utils.escape('<script/>"& &'); // '<script/>"&
x26;amp;'
...
function base64encode(s, urlsafe) { if (!Buffer.isBuffer(s)) { s = new Buffer(s); } var encode = s.toString('base64'); if (urlsafe) { encode = encode.replace(/\+/g, '-').replace(/\//g, '_'); } return encode; }
...
utils.hmac('sha1', 'I am a key', 'hello world'); // 'pO6J0LKDxRRkvSECSEdxwKx84L0='
```
### decode and encode
```js
// base64 encode
utils.base64encode('你好¥'); // '5L2g5aW977+l'
utils.base64decode('5L2g5aW977+l') // '你好¥'
// urlsafe base64 encode
utils.base64encode('你好¥', true); // '5L2g5aW977-l'
utils.base64decode('5L2g5aW977-l', true); // '你好¥'
// html escape
...
function hash(method, s, format) { var sum = crypto.createHash(method); var isBuffer = Buffer.isBuffer(s); if (!isBuffer && typeof s === 'object') { s = JSON.stringify(sortObject(s)); } sum.update(s, isBuffer ? 'binary' : 'utf8'); return sum.digest(format || 'hex'); }
...
*
* @param {String|Buffer} s
* @param {String} [format] output string format, could be 'hex' or 'base64'. default is 'hex'.
* @return {String} md5 hash string
* @public
*/
exports.md5 = function md5(s, format) {
return exports.hash('md5', s, format);
};
/**
* sha1 hash
*
* @param {String|Buffer} s
* @param {String} [format] output string format, could be 'hex' or 'base64'. default is 'hex'.
...
function hmac(algorithm, key, data, encoding) { encoding = encoding || 'base64'; var hmac = crypto.createHmac(algorithm, key); hmac.update(data, Buffer.isBuffer(data) ? 'binary' : 'utf8'); return hmac.digest(encoding); }
...
utils.sha256(new Buffer('苏千')).should.equal('75dd03e3fcdbba7d5bec07900bae740cc8e361d77e7df8949de421d3df5d3635'
;);
```
### hmac
```js
// hmac-sha1 with base64 output encoding
utils.hmac('sha1', 'I am a key', 'hello world'); // '
;pO6J0LKDxRRkvSECSEdxwKx84L0='
```
### decode and encode
```js
// base64 encode
utils.base64encode('你好¥'); // '5L2g5aW977+l'
...
function md5(s, format) { return exports.hash('md5', s, format); }
...
```js
const utils = require('utility');
```
### md5
```js
utils.md5('苏千').should.equal('5f733c47c58a077d61257102b2d44481');
utils.md5(new Buffer('苏千')).should.equal('5f733c47c58a077d61257102b2d44481');
// md5 base64 format
utils.md5('苏千', 'base64'); // 'X3M8R8WKB31hJXECstREgQ=='
// Object md5 hash. Sorted by key, and JSON.stringify. See source code for detail
utils.md5({foo: 'bar', bar: 'foo'}).should.equal(utils.md5({bar: 'foo', foo: 'bar'}));
```
...
function sha1(s, format) { return exports.hash('sha1', s, format); }
...
// Object md5 hash. Sorted by key, and JSON.stringify. See source code for detail
utils.md5({foo: 'bar', bar: 'foo'}).should.equal(utils.md5({bar: 'foo', foo: 'bar'}));
```
### sha1
```js
utils.sha1('苏千').should.equal('0a4aff6bab634b9c2f99b71f25e976921fcde5a5
');
utils.sha1(new Buffer('苏千')).should.equal('0a4aff6bab634b9c2f99b71f25e976921fcde5a5');
// sha1 base64 format
utils.sha1('苏千', 'base64'); // 'Ckr/a6tjS5wvmbcfJel2kh/N5aU='
// Object sha1 hash. Sorted by key, and JSON.stringify. See source code for detail
utils.sha1({foo: 'bar', bar: 'foo'}).should.equal(utils.sha1({bar: 'foo', foo: 'bar'}));
```
...
function sha1(s, format) { return exports.hash('sha256', s, format); }
...
// Object sha1 hash. Sorted by key, and JSON.stringify. See source code for detail
utils.sha1({foo: 'bar', bar: 'foo'}).should.equal(utils.sha1({bar: 'foo', foo: 'bar'}));
```
### sha256
```js
utils.sha256(new Buffer('苏千')).should.equal('75dd03e3fcdbba7d5bec07900bae740cc8e361d77e7df8949de421d3df5d3635
');
```
### hmac
```js
// hmac-sha1 with base64 output encoding
utils.hmac('sha1', 'I am a key', 'hello world'); // 'pO6J0LKDxRRkvSECSEdxwKx84L0='
...
function YYYYMMDD(d, sep) { if (typeof d === 'string') { // YYYYMMDD(sep) sep = d; d = new Date(); } else { // YYYYMMDD(d, sep) d = d || new Date(); if (typeof sep !== 'string') { sep = '-'; } } var date = d.getDate(); if (date < 10) { date = '0' + date; } var month = d.getMonth() + 1; if (month < 10) { month = '0' + month; } return d.getFullYear() + sep + month + sep + date; }
...
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
...
YYYYMMDDHHmmss = function (d, options) { d = d || new Date(); if (!(d instanceof Date)) { d = new Date(d); } var dateSep = '-'; var timeSep = ':'; if (options) { if (options.dateSep) { dateSep = options.dateSep; } if (options.timeSep) { timeSep = options.timeSep; } } var date = d.getDate(); if (date < 10) { date = '0' + date; } var month = d.getMonth() + 1; if (month < 10) { month = '0' + month; } var hours = d.getHours(); if (hours < 10) { hours = '0' + hours; } var mintues = d.getMinutes(); if (mintues < 10) { mintues = '0' + mintues; } var seconds = d.getSeconds(); if (seconds < 10) { seconds = '0' + seconds; } return d.getFullYear() + dateSep + month + dateSep + date + ' ' + hours + timeSep + mintues + timeSep + seconds; }
...
// 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'
...
YYYYMMDDHHmmssSSS = function (d, msSep) { if (typeof d === 'string') { // logDate(msSep) msSep = d; d = new Date(); } else { // logDate(d, msSep) d = d || new Date(); } var date = d.getDate(); if (date < 10) { date = '0' + date; } var month = d.getMonth() + 1; if (month < 10) { month = '0' + month; } var hours = d.getHours(); if (hours < 10) { hours = '0' + hours; } var mintues = d.getMinutes(); if (mintues < 10) { mintues = '0' + mintues; } var seconds = d.getSeconds(); if (seconds < 10) { seconds = '0' + seconds; } var milliseconds = d.getMilliseconds(); if (milliseconds < 10) { milliseconds = '00' + milliseconds; } else if (milliseconds < 100) { milliseconds = '0' + milliseconds; } return d.getFullYear() + '-' + month + '-' + date + ' ' + hours + ':' + mintues + ':' + seconds + (msSep || '.') + milliseconds; }
...
```js
// 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
...
accessLogDate = function (d) { // 16/Apr/2013:16:40:09 +0800 d = d || new Date(); var date = d.getDate(); if (date < 10) { date = '0' + date; } var hours = d.getHours(); if (hours < 10) { hours = '0' + hours; } var mintues = d.getMinutes(); if (mintues < 10) { mintues = '0' + mintues; } var seconds = d.getSeconds(); if (seconds < 10) { seconds = '0' + seconds; } return date + '/' + MONTHS[d.getMonth()] + '/' + d.getFullYear() + ':' + hours + ':' + mintues + ':' + seconds + TIMEZONE; }
...
}
```
### Date utils
```js
// 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'
...
datestruct = function (now) { now = now || new Date(); return { YYYYMMDD: now.getFullYear() * 10000 + (now.getMonth() + 1) * 100 + now.getDate(), H: now.getHours() }; }
...
// '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)
...
logDate = function (d, msSep) { if (typeof d === 'string') { // logDate(msSep) msSep = d; d = new Date(); } else { // logDate(d, msSep) d = d || new Date(); } var date = d.getDate(); if (date < 10) { date = '0' + date; } var month = d.getMonth() + 1; if (month < 10) { month = '0' + month; } var hours = d.getHours(); if (hours < 10) { hours = '0' + hours; } var mintues = d.getMinutes(); if (mintues < 10) { mintues = '0' + mintues; } var seconds = d.getSeconds(); if (seconds < 10) { seconds = '0' + seconds; } var milliseconds = d.getMilliseconds(); if (milliseconds < 10) { milliseconds = '00' + milliseconds; } else if (milliseconds < 100) { milliseconds = '0' + milliseconds; } return d.getFullYear() + '-' + month + '-' + date + ' ' + hours + ':' + mintues + ':' + seconds + (msSep || '.') + milliseconds; }
...
```js
// 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'
...
function timestamp(t) { if (t) { var v = t; if (typeof v === 'string') { v = Number(v); } if (String(t).length === 10) { v *= 1000; } return new Date(v); } return Math.round(Date.now() / 1000); }
...
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)
```
...
function getParamNames(func, cache) { cache = cache !== false; if (cache && func.__cache_names) { return func.__cache_names; } var str = func.toString(); var names = str.slice(str.indexOf('(') + 1, str.indexOf(')')).match(/([^\s,]+)/g) || []; func.__cache_names = names; return names; }
...
### others
___[WARNNING] getIP() remove, PLEASE use `https://github.com/node-modules/address` module instead.___
```js
// 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
...
function noop() {}
n/a
strictJSONParse = function (str) { var obj = JSON.parse(str); if (!obj || typeof obj !== 'object') { throw new Error('JSON string is not object'); } return obj; }
n/a
function isSafeNumberString(s) { if (s[0] === '-') { s = s.substring(1); } if (s.length < MAX_SAFE_INTEGER_STR_LENGTH || (s.length === MAX_SAFE_INTEGER_STR_LENGTH && s <= MAX_SAFE_INTEGER_STR)) { return true; } return false; }
...
utils.timestamp(1385091596000); // Fri Nov 22 2013 11:39:56 GMT+0800 (CST)
```
### Number utils
```js
// 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.
...
function random(lower, upper) { if (lower === undefined && upper === undefined) { return 0; } if (upper === undefined) { upper = lower; lower = 0; } var temp; if (lower > upper) { temp = lower; lower = upper; upper = temp; } return Math.floor(lower + Math.random() * (upper - lower)); }
...
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
```
### Timers
```js
...
function toSafeNumber(s) { if (typeof s === 'number') { return s; } return exports.isSafeNumberString(s) ? Number(s) : s; }
...
```js
// 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
```
...
assign = function (target, objects) { if (!Array.isArray(objects)) { objects = [ objects ]; } for (var i = 0; i < objects.length; i++) { var obj = objects[i]; if (obj) { var keys = Object.keys(obj); for (var j = 0; j < keys.length; j++) { var key = keys[j]; target[key] = obj[key]; } } } return target; }
...
```
### Object.assign
```js
// assign object
utility.assign({}, { a: 1 });
// assign multiple object
utility.assign({}, [ { a: 1 }, { b: 1 } ]);
```
## benchmark
...
function has(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); }
...
// 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 () {}
}
```
### Date utils
...
function map(obj) { var map = new EmptyObject(); if (!obj) { return map; } for (var key in obj) { map[key] = obj[key]; } return map; }
...
### map
Create a `real` map in javascript.
use `Object.create(null)`
```js
const map = utils.map({a: 1});
// should.not.exist(map.constractor);
// should.not.exist(map.__proto__);
// should.not.exist(map.toString);
// should not exist any property
console.log(map); // {a: 1}
...
argumentsToArray = function (args) { var res = new Array(args.length); for (var i = 0; i < args.length; i++) { res[i] = args[i]; } return res; }
...
// {error: Error, value: undefined}
```
### argumentsToArray
```js
function() {
const arr = utility.argumentsToArray(arguments);
console.log(arr.join(', '));
}
```
### JSON
```js
...
dig = function (obj) { if (!obj) { return; } if (arguments.length <= 1) { return obj; } var value = obj[arguments[1]]; for (var i = 2; i < arguments.length; i++) { if (!value) { break; } value = value[arguments[i]]; } return value; }
n/a
try = function (fn) { var res = { error: undefined, value: undefined }; try { res.value = fn(); } catch (err) { res.error = err instanceof Error ? err : new Error(err); } return res; }
...
// replace http header invalid characters
utils.replaceInvalidHttpHeaderChar('abc你好11'); // {invalid: true, val: 'abc 11'}
```
### Try
```js
const res = utils.try(function () {
return JSON.parse(str);
});
// {error: undefined, value: {foo: 'bar'}}
// {error: Error, value: undefined}
```
...
setImmediate = function () {
/*
* this function will do nothing
*/
return;
}
...
utils.random(2, 1000); // [2, 1000)
utils.random(); // 0
```
### Timers
```js
utils.setImmediate(function () {
console.log('hi');
});
```
### map
Create a `real` map in javascript.
...
function includesInvalidHttpHeaderChar(val) { if (!val || typeof val !== 'string') { return false; } for (var i = 0; i < val.length; ++i) { if (!validHdrChars[val.charCodeAt(i)]) { return true; } } return false; }
n/a
function randomString(length, charSet) { var result = []; length = length || 16; charSet = charSet || 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; while (length--) { result.push(charSet[Math.floor(Math.random() * charSet.length)]); } return result.join(''); }
...
___[WARNNING] getIP() remove, PLEASE use `https://github.com/node-modules/address` module instead.___
```js
// 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 () {}
}
...
function replace(str, substr, newSubstr) { var replaceFunction = newSubstr; if (typeof replaceFunction !== 'function') { replaceFunction = function () { return newSubstr; }; } return str.replace(substr, replaceFunction); }
...
### String utils
```js
// 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>', '$
x26; body'); // '$& body hi'
// replace http header invalid characters
utils.replaceInvalidHttpHeaderChar('abc你好11'); // {invalid: true, val: 'abc 11'}
```
### Try
...
function replaceInvalidHttpHeaderChar(val, replacement) { replacement = replacement || ' '; var invalid = false; if (!val || typeof val !== 'string') { return { val: val, invalid: invalid, }; } var replacementType = typeof replacement; var chars; for (var i = 0; i < val.length; ++i) { if (!validHdrChars[val.charCodeAt(i)]) { // delay create chars chars = chars || val.split(''); if (replacementType === 'function') { chars[i] = replacement(chars[i]); } else { chars[i] = replacement; } } } if (chars) { val = chars.join(''); invalid = true; } return { val: val, invalid: invalid, }; }
...
// 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
```js
const res = utils.try(function () {
return JSON.parse(str);
...
function split(str, sep) { str = str || ''; sep = sep || ','; var items = str.split(sep); var needs = []; for (var i = 0; i < items.length; i++) { var s = items[i].trim(); if (s.length > 0) { needs.push(s); } } return needs; }
...
console.log(map); // {a: 1}
```
### String utils
```js
// 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'}
```
...
function splitAlwaysOptimized() { var str = ''; var sep = ','; if (arguments.length === 1) { str = arguments[0] || ''; } else if (arguments.length === 2) { str = arguments[0] || ''; sep = arguments[1] || ','; } var items = str.split(sep); var needs = []; for (var i = 0; i < items.length; i++) { var s = items[i].trim(); if (s.length > 0) { needs.push(s); } } return needs; }
n/a
function decodeURIComponent_(encodeText) { try { return decodeURIComponent(encodeText); } catch (e) { return encodeText; } }
...
utils.base64encode('你好¥', true); // '5L2g5aW977-l'
utils.base64decode('5L2g5aW977-l', true); // '你好¥'
// html escape
utils.escape('<script/>"& &'); // '<script/>"&
x26;amp;'
// Safe encodeURIComponent and decodeURIComponent
utils.decodeURIComponent(utils.encodeURIComponent('你好, nodejs')).should.equal
('你好, nodejs');
```
### others
___[WARNNING] getIP() remove, PLEASE use `https://github.com/node-modules/address` module instead.___
```js
...
function encodeURIComponent_(text) { try { return encodeURIComponent(text); } catch (e) { return text; } }
...
utils.base64encode('你好¥', true); // '5L2g5aW977-l'
utils.base64decode('5L2g5aW977-l', true); // '你好¥'
// html escape
utils.escape('<script/>"& &'); // '<script/>"&
x26;amp;'
// Safe encodeURIComponent and decodeURIComponent
utils.decodeURIComponent(utils.encodeURIComponent('你好, nodejs')).should.equal
('你好, nodejs');
```
### others
___[WARNNING] getIP() remove, PLEASE use `https://github.com/node-modules/address` module instead.___
```js
...
function escapeHtml(string) { var str = '' + string; var match = matchHtmlRegExp.exec(str); if (!match) { return str; } var escape; var html = ''; var index = 0; var lastIndex = 0; for (index = match.index; index < str.length; index++) { switch (str.charCodeAt(index)) { case 34: // " escape = '"'; break; case 38: // & escape = '&'; break; case 39: // ' escape = '''; break; case 60: // < escape = '<'; break; case 62: // > escape = '>'; break; default: continue; } if (lastIndex !== index) { html += str.substring(lastIndex, index); } lastIndex = index + 1; html += escape; } return lastIndex !== index ? html + str.substring(lastIndex, index) : html; }
...
utils.base64decode('5L2g5aW977+l') // '你好¥'
// urlsafe base64 encode
utils.base64encode('你好¥', true); // '5L2g5aW977-l'
utils.base64decode('5L2g5aW977-l', true); // '你好¥'
// html escape
utils.escape('<script/>"& &'); // '&
lt;script/>"& &'
// Safe encodeURIComponent and decodeURIComponent
utils.decodeURIComponent(utils.encodeURIComponent('你好, nodejs')).should.equal('你好, nodejs');
```
### others
...