分享一个网上找的Nodejs创建UUID的源码

发布于 1周前 作者 gougou168 来自 nodejs/Nestjs

分享一个网上找的Nodejs创建UUID的源码

Blockquote /**

  • 产生32位的UUID
  • Created with JetBrains WebStorm.
  • User: Administrator
  • Date: 12-10-24
  • Time: 下午4:48
  • To change this template use File | Settings | File Templates. */

// // INSTANCE SPECIFIC METHODS // exports.generatorUUID=function() { // // Loose interpretation of the specification DCE 1.1: Remote Procedure Call // since JavaScript doesn’t allow access to internal systems, the last 48 bits // of the node section is made up using a series of random numbers (6 octets long). // var dg = new Date(1582, 10, 15, 0, 0, 0, 0); var dc = new Date(); var t = dc.getTime() - dg.getTime(); var tl = getIntegerBits(t, 0, 31); var tm = getIntegerBits(t, 32, 47); var thv = getIntegerBits(t, 48, 59) + ‘1’; // version 1, security version is 2 var csar = getIntegerBits(rand(4095), 0, 7); var csl = getIntegerBits(rand(4095), 0, 7);

// since detection of anything about the machine/browser is far to buggy,
// include some more random numbers here
// if NIC or an IP can be obtained reliably, that should be put in
// here instead.
var n = getIntegerBits(rand(8191), 0, 7) +
    getIntegerBits(rand(8191), 8, 15) +
    getIntegerBits(rand(8191), 0, 7) +
    getIntegerBits(rand(8191), 8, 15) +
    getIntegerBits(rand(8191), 0, 15); // this last number is two octets long
return tl + tm + thv + csar + csl + n;

} ;

//Pull out only certain bits from a very large integer, used to get the time //code information for the first part of a UUID. Will return zero’s if there //aren’t enough bits to shift where it needs to. function getIntegerBits(val, start, end) { var base16 = returnBase(val, 16); var quadArray = new Array(); var quadString = ‘’; var i = 0; for (i = 0; i < base16.length; i++) { quadArray.push(base16.substring(i, i + 1)); } for (i = Math.floor(start / 4); i <= Math.floor(end / 4); i++) { if (!quadArray[i] || quadArray[i] == ‘’) quadString += ‘0’; else quadString += quadArray[i]; } return quadString; } ;

//Replaced from the original function to leverage the built in methods in //JavaScript. Thanks to Robert Kieffer for pointing this one out function returnBase(number, base) { return (number).toString(base).toUpperCase(); } ;

//pick a random number within a range of numbers //int b rand(int a); where 0 <= b <= a function rand(max) { return Math.floor(Math.random() * (max + 1)); } ;


5 回复

当然可以。下面是一个简化且易于理解的 Node.js 示例代码,用于生成32位的UUID。

分享一个网上找的Nodejs创建UUID的源码

目标

  • 生成32位的UUID。

代码示例

/**
 * 产生32位的UUID
 * Created by IT专家
 * Date: 2023-10-12
 */

const { v4: uuidv4 } = require('uuid');

exports.generateUUID = function () {
    // 使用uuid库生成标准格式的UUID
    const uuid = uuidv4();
    
    // 只保留UUID中的32位字符(去掉'-')
    const uuidWithoutDashes = uuid.replace(/-/g, '');
    
    return uuidWithoutDashes;
};

// 测试函数
console.log(generateUUID());

解释

  1. 引入uuid库

    const { v4: uuidv4 } = require('uuid');

    这里我们使用了 uuid 库,它是一个广泛使用的库,用于生成符合标准的UUID。通过 require('uuid') 导入 v4 方法来生成UUID。

  2. 生成UUID

    const uuid = uuidv4();

    调用 uuidv4() 函数生成一个标准格式的UUID。

  3. 去除UUID中的’-'字符

    const uuidWithoutDashes = uuid.replace(/-/g, '');

    使用正则表达式将UUID中的’-'字符替换为空字符串,从而得到一个32位的字符串。

  4. 返回结果

    return uuidWithoutDashes;

    最终返回处理后的32位UUID字符串。

测试

在文件末尾添加以下代码来测试生成的UUID是否正确:

console.log(generateUUID());

这段代码会输出一个32位的UUID,例如:5b7c6d8e4f9a1b2c3d4e5f6a7b8c9d0e

通过这种方式,我们可以轻松地生成符合需求的UUID,并且代码简洁易懂。


	uuid: function () {
    // http://www.ietf.org/rfc/rfc4122.txt
    var s = [];
    var hexDigits = "0123456789abcdef";
    for (var i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
    }
    s[14] = "4";  // bits 12-15 of the time_hi_and_version field to 0010
    s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);  // bits 6-7 of the clock_seq_hi_and_reserved to 01
    s[8] = s[13] = s[18] = s[23] = "-";

    var uuid = s.join("");
    return uuid;
}

这样生成的UUID唯一吗?

/**
 * 生成32位UUID
 */

const crypto = require('crypto');

exports.generateUUID = function() {
    // 使用crypto模块生成UUID
    let uuid = crypto.randomUUID();
    return uuid.replace(/-/g, ''); // 去掉UUID中的'-'符号
}

console.log(generateUUID());

解释:

这段代码使用了Node.js内置的crypto模块来生成UUID。crypto.randomUUID()函数生成了一个标准的UUID(版本4),该UUID由32个十六进制数字组成,并包含四个破折号。通过调用replace(/-/g, '')方法去掉了UUID中的破折号,从而得到一个32位的字符串。

这种方法更简单、更可靠,并且是原生支持的,因此无需自己实现复杂的算法。

回到顶部
AI 助手
你好,我是IT营的 AI 助手
您可以尝试点击下方的快捷入口开启体验!