它的原理就是从数字经过一个加盐(salted)算法产生一个哈希(hash)字符串。这样算法就是通过混淆使结果具有不可预测性,而唯一性依然由数字本身来达成,从而得到(类似 youtube 里的)足够短,不可预测且唯一的 ID。
安装:
npm install hashids
简单例子:
let Hashids = require( 'hashids');
let hashids = new Hashids();
let id = hashids. encode( '1'); //jR
let numbers = hashids. decode(id); //[1]
更多选项:
- encode多种写法 let Hashids = require( 'hashids');let hashids = new Hashids();console. log(hashids. encode( 1, 2, 3)); // o2fXhVconsole. log(hashids. encode([ 1, 2, 3])); // o2fXhVconsole. log(hashids. encode( '1', '2', '3')); // o2fXhVconsole. log(hashids. encode([ '1', '2', '3'])); // o2fXhV
- 通过项目名称,使ids唯一let hashids = new Hashids( 'My Project');console. log(hashids. encode( 1, 2, 3)); // Z4UrtWlet hashids = new Hashids( 'My Other Project');console. log(hashids. encode( 1, 2, 3)); // gPUasb
- ids长度 let hashids = new Hashids(); // no paddingconsole. log(hashids. encode( 1)); // jRlet hashids = new Hashids( '', 10); // pad to length 10console. log(hashids. encode( 1)); // VolejRejNm
- 自定义ids显示字母 let hashids = new Hashids ( '' , 0 , 'abcdefghijklmnopqrstuvwxyz' ); // all lowercaseconsole. log(hashids. encode( 1, 2, 3)); // mdfphx//Default alphabet is abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890//至少16个唯一的字母
- 编码十六机制而不是数字
let id = hashids. encodeHex( '507f1f77bcf86cd799439011'); // y42LW46J9luq3Xq9XMlylet hex = hashids. decodeHex(id); // 507f1f77bcf86cd799439011
陷阱:
- 尽管仅仅加密一个数字,返回的也是数组
- 不支持负数加密
- 如加密的不是数组,则返回空字符串 let id = hashids. encode( '123a');console. log(id === ''); // true