nodejs 生成uid(唯一标识符) —— node uuid模块的使用

Node.js生成UUID详解
本文详细介绍了如何在Node.js环境中使用node-uuid模块生成UUID(唯一标识符)。涵盖了基于时间、随机数及命名空间的不同版本UUID的生成方法,并提供了丰富的代码示例。

nodejs 提供了一个 node-uuid 模块用于生成 uuid(唯一标识符)

  • 首先执行 :

  npm install node-uuid
  • es6引入

  import uuid from 'node-uuid';//或者 const uuidv1 = require('uuid/v1');
 
 console.log(uuid.v1());//'6c84fb90-12c4-11e1-840d-7b25c5ee775a' ;
  console.log(uuid.v4());//'110ec58a-a0f2-4ac4-8393-c866d813b8d1'
 

 

  • UUID 定义

UUID 是由一组 32 位的 16 进制数所构成,是故 UUID 理论上的总数为 1632=2128,约等于 3.4 x 10^38。也就是说若每纳秒产生 1 个 UUID,要花 100 亿年才会将所有 UUID 用完。

UUID 示例:74760410-f963-11e8-b2a3-1bb26e1e5b69

  • UUID 版本

  1. "版本 1" UUID 是根据时间和节点 ID(通常是 MAC 地址)生成;
  2. "版本 2" UUID 是根据标识符(通常是组或用户 ID)、时间和节点 ID 生成;
  3. "版本 3" 和 "版本 5" 确定性 UUID 通过散列 (hashing) 命名空间 (namespace) 标识符和名称生成;
  4. "版本 4" UUID 使用随机性伪随机性生成。
  • Node.js uuid 模块示例

在 JavaScript 中生成符合 RFC 规范的 UUID。

  • 版本 1:基于时间的 UUID

 

const uuidv1 = require('uuid/v1');
uuidv1() //  ⇨ 43d7e120-f963-11e8-999e-51f3e5aa256f

const formatedUUID = uuidv1().replace(/-/g, ''); // 去除横线-
  • 版本 2:DCE 安全的 UUID

未实现。

  • 版本 3:基于名字空间的 UUID(MD5)

 

const uuidv3 = require('uuid/v3');

// ... using predefined DNS namespace (for domain names)
uuidv3('hello.example.com', uuidv3.DNS); // ⇨ '9125a8dc-52ee-365b-a5aa-81b0b3681cf6'

// ... using predefined URL namespace (for, well, URLs)
uuidv3('http://example.com/hello', uuidv3.URL); // ⇨ 'c6235813-3ba4-3801-ae84-e0a6ebb7d138'

// ... using a custom namespace
//
// Note: Custom namespaces should be a UUID string specific to your application!
// E.g. the one here was generated using this modules `uuid` CLI.
const MY_NAMESPACE = '1b671a64-40d5-491e-99b0-da01ff1f3341';
uuidv3('Hello, World!', MY_NAMESPACE); // ⇨ 'e8b5a51d-11c8-3310-a6ab-367563f20686'

版本 4:基于随机数的 UUID

 

const uuidv4 = require('uuid/v4');
uuidv4(); // ⇨ 57751a52-db27-4b2f-8a08-7e02f9e94a42

版本 5:基于名字空间的 UUID(SHA1)

 

const uuidv5 = require('uuid/v5');

// ... using predefined DNS namespace (for domain names)
uuidv5('hello.example.com', uuidv5.DNS); // ⇨ 'fdda765f-fc57-5604-a269-52a7df8164ec'

// ... using predefined URL namespace (for, well, URLs)
uuidv5('http://example.com/hello', uuidv5.URL); // ⇨ '3bbcee75-cecc-5b56-8031-b6641c1ed1f1'

// ... using a custom namespace
//
// Note: Custom namespaces should be a UUID string specific to your application!
// E.g. the one here was generated using this modules `uuid` CLI.
const MY_NAMESPACE = '1b671a64-40d5-491e-99b0-da01ff1f3341';
uuidv5('Hello, World!', MY_NAMESPACE); // ⇨ '630eb68f-e0fa-5ecc-887a-7c7a62614681'

参考

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值