Skip to content

Latest commit

 

History

History
29 lines (20 loc) · 1005 Bytes

UUIDGeneratorNode.md

File metadata and controls

29 lines (20 loc) · 1005 Bytes
标题 标签
UUIDGeneratorNode(在 node.js 中生成 UUID) node,random,intermediate(node 环境,随机,两者之间)

在node.js中生成 UUID。

  • 使用Crypto.getRandomValues()生成符合RFC4122版本 4 的 UUID。
  • 使用Number.prototype.toString(16)将其转换为合适的 UUID。

代码如下:

const crypto = require('crypto');

const UUIDGeneratorNode = () =>
  ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c =>
    (c ^ (crypto.randomBytes(1)[0] & (15 >> (c / 4)))).toString(16)
  );

调用方式:

UUIDGeneratorNode(); // '79c7c136-60ee-40a2-beb2-856f1feabefc'

应用场景