首页
/ UUID 项目技术文档

UUID 项目技术文档

2024-12-20 09:55:19作者:柏廷章Berta

1. 安装指南

1.1 使用 npm 安装

要安装 uuid 库,请在终端中运行以下命令:

npm install uuid

1.2 使用 yarn 安装

如果你使用的是 yarn,可以运行以下命令:

yarn add uuid

2. 项目的使用说明

2.1 创建 UUID

2.1.1 使用 ECMAScript 模块语法

import { v4 as uuidv4 } from 'uuid';

const myUUID = uuidv4(); // 生成一个随机的 UUID
console.log(myUUID); // 例如:'9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d'

2.1.2 使用 CommonJS 模块语法

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

const myUUID = uuidv4(); // 生成一个随机的 UUID
console.log(myUUID); // 例如:'1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed'

2.2 生成不同版本的 UUID

uuid 库支持多种版本的 UUID 生成,包括:

  • v1: 基于时间戳的 UUID
  • v3: 基于命名空间和 MD5 的 UUID
  • v4: 基于随机数的 UUID
  • v5: 基于命名空间和 SHA-1 的 UUID
  • v6: 基于时间戳的重排序 UUID
  • v7: 基于 Unix Epoch 时间戳的 UUID

例如,生成一个基于时间戳的 UUID:

import { v1 as uuidv1 } from 'uuid';

const timestampUUID = uuidv1();
console.log(timestampUUID); // 例如:'2c5ea4c0-4067-11e9-9bdd-2b0d7b3dcb6d'

3. 项目 API 使用文档

3.1 uuid.NIL

返回一个全为零的 UUID 字符串(nil UUID)。

import { NIL as NIL_UUID } from 'uuid';

console.log(NIL_UUID); // '00000000-0000-0000-0000-000000000000'

3.2 uuid.MAX

返回一个全为 1 的 UUID 字符串(最大 UUID)。

import { MAX as MAX_UUID } from 'uuid';

console.log(MAX_UUID); // 'ffffffff-ffff-ffff-ffff-ffffffffffff'

3.3 uuid.parse(str)

将 UUID 字符串转换为字节数组。

import { parse as uuidParse } from 'uuid';

const bytes = uuidParse('6ec0bd7f-11c0-43da-975e-2a8ad9ebae0b');
console.log(bytes); // Uint8Array(16) [110, 192, 189, 127, 17, 192, 67, 218, 151, 94, 42, 138, 217, 235, 174, 11]

3.4 uuid.stringify(arr[, offset])

将字节数组转换为 UUID 字符串。

import { stringify as uuidStringify } from 'uuid';

const uuidBytes = Uint8Array.of(
  0x6e, 0xc0, 0xbd, 0x7f, 0x11, 0xc0, 0x43, 0xda, 0x97, 0x5e, 0x2a, 0x8a, 0xd9, 0xeb, 0xae, 0x0b
);

const uuidStr = uuidStringify(uuidBytes);
console.log(uuidStr); // '6ec0bd7f-11c0-43da-975e-2a8ad9ebae0b'

3.5 uuid.v1([options[, buffer[, offset]]])

生成一个基于时间戳的 UUID(版本 1)。

import { v1 as uuidv1 } from 'uuid';

const options = {
  node: Uint8Array.of(0x01, 0x23, 0x45, 0x67, 0x89, 0xab),
  clockseq: 0x1234,
  msecs: new Date('2011-11-01').getTime(),
  nsecs: 5678,
};

const timestampUUID = uuidv1(options);
console.log(timestampUUID); // '710b962e-041c-11e1-9234-0123456789ab'

3.6 uuid.v4([options[, buffer[, offset]]])

生成一个基于随机数的 UUID(版本 4)。

import { v4 as uuidv4 } from 'uuid';

const randomUUID = uuidv4();
console.log(randomUUID); // 例如:'9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d'

3.7 uuid.v5(name, namespace[, buffer[, offset]])

生成一个基于命名空间和 SHA-1 的 UUID(版本 5)。

import { v5 as uuidv5 } from 'uuid';

const namespace = '6ba7b810-9dad-11d1-80b4-00c04fd430c8';
const name = 'example.com';

const sha1UUID = uuidv5(name, namespace);
console.log(sha1UUID); // 例如:'c106a26a-21bb-5d9c-8b5e-3b2f4f6d6c0a'

4. 项目安装方式

4.1 使用 npm 安装

npm install uuid

4.2 使用 yarn 安装

yarn add uuid

通过以上步骤,你可以轻松安装并使用 uuid 库来生成符合 RFC4122 标准的 UUID。

登录后查看全文
热门项目推荐
相关项目推荐