====== uuid ======
Для создания [[http://www.ietf.org/rfc/rfc4122.txt|RFC4122]] UUIDs
* **Complete** - Поддержка RFC4122 версий 1, 3, 4 и 5 UUID
* **Cross-platform** - Поддержка для ...
* CommonJS, [[#ecmascript-modules|ECMAScript Modules]] и [[#cdn-builds|CDN builds]]
* Node 8, 10, 12, 14
* Chrome, Safari, Firefox, Edge, IE 11 browsers
* Webpack and rollup.js module bundlers
* [[#react-native--expo|React Native / Expo]]
* **Secure** - Cryptographically-strong random values
* **Small** - Отсутствие зависимости, небольшой размер, хорошо сочетается с упаковщиками
* **CLI** - Включает ''[[#command-line|uuid]]''[[#command-line| command line]] утилита
**Обновление с ''uuid@3.x''?** Ваш код, вероятно будет в порядке, но проверьте [[#upgrading-from-uuid3x|Upgrading From ]]''[[#upgrading-from-uuid3x|uuid@3.x]]'' для подробностей.
=====Быстрый старт=====
Чтобы создать случайный UUID ...
**1. Install**
npm install uuid
** 2. Создайте UUID ** (синтаксис модуля ES6)
import { v4 as uuidv4 } from 'uuid';
uuidv4(); // ⇨ '9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d'
... или используя синтаксис CommonJS:
const { v4: uuidv4 } = require('uuid');
uuidv4(); // ⇨ '1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed'
Для UUID меток времени, UUID пространств имен и других параметров читайте дальше ...
===== API Summary =====
^ ^ ^ ^
|''[[#uuidnil|uuid.NIL]]''|The nil UUID string (all zeros)|New in ''uuid@8.3''|
|''[[#uuidparsestr|uuid.parse()]]''|Convert UUID string to array of bytes|New in ''uuid@8.3''|
|''[[#uuidstringifyarr-offset|uuid.stringify()]]''|Convert array of bytes to UUID string|New in ''uuid@8.3''|
|''[[#uuidv1options-buffer-offset|uuid.v1()]]''|Create a version 1 (timestamp) UUID| |
|''[[#uuidv3name-namespace-buffer-offset|uuid.v3()]]''|Create a version 3 (namespace w/ MD5) UUID| |
|''[[#uuidv4options-buffer-offset|uuid.v4()]]''|Create a version 4 (random) UUID| |
|''[[#uuidv5name-namespace-buffer-offset|uuid.v5()]]''|Create a version 5 (namespace w/ SHA-1) UUID| |
|''[[#uuidvalidatestr|uuid.validate()]]''|Test a string to see if it is a valid UUID|New in ''uuid@8.3''|
|''[[#uuidversionstr|uuid.version()]]''|Detect RFC version of a UUID|New in ''uuid@8.3''|
===== API =====
==== uuid.NIL ====
Строка нулевого UUID (все нули).
Example:
import { NIL as NIL_UUID } from 'uuid';
NIL_UUID; // ⇨ '00000000-0000-0000-0000-000000000000'
==== uuid.parse(str) ====
Преобразовать строку UUID в массив байтов
^ ^ ||''str''|A valid UUID ''String''|
|returns|''Uint8Array[16]''|
|throws|''TypeError'' if ''str'' is not a valid UUID|
Примечание. Порядок значений в байтовых массивах, используемых функциями parse () и stringify (), соответствует порядку шестнадцатеричных пар слева ↠ справа в строках UUID. Как показано в примере ниже.
пример:
import { parse as uuidParse } from 'uuid';
// Parse a UUID
const bytes = uuidParse('6ec0bd7f-11c0-43da-975e-2a8ad9ebae0b');
// Convert to hex strings to show byte order (for documentation purposes)
[...bytes].map((v) => v.toString(16).padStart(2, '0')); // ⇨
// [
// '6e', 'c0', 'bd', '7f',
// '11', 'c0', '43', 'da',
// '97', '5e', '2a', '8a',
// 'd9', 'eb', 'ae', '0b'
// ]
==== uuid.stringify(arr[, offset]) ====
Преобразовать массив байтов в строку UUID
^ ^ ^
|''arr''|''Array''-like collection of 16 values (starting from ''offset'') between 0-255.|
|[''offset'' = 0]|''Number'' Starting index in the Array|
|returns|''String''|
|throws|''TypeError'' если действительная строка UUID не может быть сгенерирована|
Порядок значений в байтовых массивах, используемых функциями parse () и stringify (), соответствует порядку шестнадцатеричных пар слева ↠ справа в строках UUID. Как показано в примере ниже.
Example:
import { stringify as uuidStringify } from 'uuid';
const uuidBytes = [
0x6e,
0xc0,
0xbd,
0x7f,
0x11,
0xc0,
0x43,
0xda,
0x97,
0x5e,
0x2a,
0x8a,
0xd9,
0xeb,
0xae,
0x0b,
];
uuidStringify(uuidBytes); // ⇨ '6ec0bd7f-11c0-43da-975e-2a8ad9ebae0b'
==== uuid.v1%%([%%options[, buffer[, offset]]]) ====
Создайте UUID RFC версии 1 (отметка времени)
^ ^ ^
|[''options'']|''Object'' с одним или несколькими из следующих свойств:|
|[''options.node'' ]|Поле RFC 'node' как '' массив [6] '' байтовых значений (согласно 4.1.6)|
|[''options.clockseq'']|RFC 'clock sequence' как 'Number' от 0 до 0x3fff|
|[''options.msecs'']|Поле RFC 'timestamp' ('' Число '' миллисекунд, эпоха unix)|
|[''options.nsecs'']|Поле RFC 'timestamp' ('' Число '' наносекунд, которое нужно добавить к '' msecs '', должно быть 0-10 000)|
|[''options.random'']|''Array'' из 16 случайных байтов (0-255)|
|[''options.rng'']|Альтернатива '' options.random '', '' Function '', которая возвращает '' Array '' из 16 случайных байтов (0-255).|
|[''buffer'']|''Array %%|%% Buffer'' Если указано, uuid будет записан здесь в байтовой форме, начиная с ''offset''|
|[''offset'' = 0]|''Number'' Индекс для начала записи байтов UUID в ''buffer''|
|returns|UUID ''String'' if no ''buffer'' указано, иначе возвращается ''buffer''|
|throws|''Error'' если запрашивается более 10M UUID / сек|
По умолчанию [[https://tools.ietf.org/html/rfc4122#section-4.1.6| id узла]] (последние 12 цифр в UUID) генерируется один раз случайным образом при запуске процесса, а затем остается неизменным на протяжении всего процесса.
'' options.random '' и '' options.rng '' имеют значение только при самом первом вызове '' v1 () '', где они могут быть переданы для инициализации внутреннего '' node '' и '' clockseq '' поля.
пример:
import { v1 as uuidv1 } from 'uuid';
uuidv1(); // ⇨ '2c5ea4c0-4067-11e9-8bad-9b1deb4d3b7d'
Пример использования ''options'':
import { v1 as uuidv1 } from 'uuid';
const v1options = {
node: [0x01, 0x23, 0x45, 0x67, 0x89, 0xab],
clockseq: 0x1234,
msecs: new Date('2011-11-01').getTime(),
nsecs: 5678,
};
uuidv1(v1options); // ⇨ '710b962e-041c-11e1-9234-0123456789ab'
==== uuid.v3(name, namespace[, buffer[, offset]]) ====
Создайте RFC версии 3 (пространство имен с MD5) UUID\\
\\
API идентичен «v5 ()», но вместо него использует «v3».
Согласно RFC, «Если обратная совместимость не является проблемой, предпочтительнее SHA-1 [версия 5]».
==== uuid.v4%%([%%options[, buffer[, offset]]]) ====
Создайте RFC версии 4 (случайный) UUID
^ ^ ^
|[''options'']|''Object'' с одним или несколькими из следующих свойств:|
|[''options.random'']|''Array'' из 16 случайных байтов (0-255)|
|[''options.rng'']|Альтернативой ''options.random'', a ''Function'' который возвращает массив из 16 случайных байтов (0-255)|
|[''buffer'']|''Array %%|%% Buffer'' Если указано, uuid будет записан здесь в байтовой форме, начиная с ''offset''|
|[''offset'' = 0]|''Number'' Индекс для начала записи байтов UUID в ''buffer''|
|returns|UUID ''String'' if no ''buffer'' указано, иначе возвращается ''buffer''|
пример:
import { v4 as uuidv4 } from 'uuid';
uuidv4(); // ⇨ '1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed'
Example using predefined ''random'' values:
import { v4 as uuidv4 } from 'uuid';
const v4options = {
random: [
0x10,
0x91,
0x56,
0xbe,
0xc4,
0xfb,
0xc1,
0xea,
0x71,
0xb4,
0xef,
0xe1,
0x67,
0x1c,
0x58,
0x36,
],
};
uuidv4(v4options); // ⇨ '109156be-c4fb-41ea-b1b4-efe1671c5836'
==== uuid.v5(name, namespace[, buffer[, offset]]) ====
Создайте UUID RFC версии 5 (пространство имен с SHA-1)
^ ^ ^
|''name''|''String %%|%% Array''|
|''namespace''|''String %%|%% Array[16]'' Namespace UUID|
|[''buffer'']|''Array %%|%% Buffer'' Если указано, uuid будет записан здесь в байтовой форме, начиная с ''offset''|
|[''offset'' = 0]|''Number'' Индекс для начала записи байтов UUID в ''buffer''|
|returns|UUID ''String'' if no ''buffer'' указано, иначе возвращается ''buffer''|
The RFC ''DNS'' and ''URL'' namespaces are available as ''v5.DNS'' and ''v5.URL''.
Пример с настраиваемым пространством имен:
import { v5 as uuidv5 } from 'uuid';
// Define a custom namespace. Readers, create your own using something like
// https://www.uuidgenerator.net/
const MY_NAMESPACE = '1b671a64-40d5-491e-99b0-da01ff1f3341';
uuidv5('Hello, World!', MY_NAMESPACE); // ⇨ '630eb68f-e0fa-5ecc-887a-7c7a62614681'
Пример с пространством имен RFC '' URL '':
import { v5 as uuidv5 } from 'uuid';
uuidv5('https://www.w3.org/', uuidv5.URL); // ⇨ 'c106a26a-21bb-5538-8bf2-57095d1976c1'
==== uuid.validate(str) ====
Проверьте строку, чтобы убедиться, что это действительный UUID
^ ^ ^
|''str''|''String'' подтверждать|
|returns|''true'' если строка является допустимым UUID, ''false'' иначе|
пример:
import { validate as uuidValidate } from 'uuid';
uuidValidate('not a UUID'); // ⇨ false
uuidValidate('6ec0bd7f-11c0-43da-975e-2a8ad9ebae0b'); // ⇨ true
Использовать''validate'' и ''version'' вместе можно выполнить проверку каждой версии, например проверять только для UUId версии 4.
import { version as uuidVersion } from 'uuid';
import { validate as uuidValidate } from 'uuid';
function uuidValidateV4(uuid) {
return uuidValidate(uuid) && uuidVersion(uuid) === 4;
}
const v1Uuid = 'd9428888-122b-11e1-b85c-61cd3cbb3210';
const v4Uuid = '109156be-c4fb-41ea-b1b4-efe1671c5836';
uuidValidateV4(v4Uuid); // ⇨ true
uuidValidateV4(v1Uuid); // ⇨ false
==== uuid.version(str) ====
Detect RFC version of a UUID
^ ^ ^
|''str''|A valid UUID ''String''|
|returns|''Number'' The RFC version of the UUID|
|throws|''TypeError'' if ''str'' is not a valid UUID|
Example:
import { version as uuidVersion } from 'uuid';
uuidVersion('45637ec4-c85f-11ea-87d0-0242ac130003'); // ⇨ 1
uuidVersion('6ec0bd7f-11c0-43da-975e-2a8ad9ebae0b'); // ⇨ 4
===== Command Line =====
UUIDs can be generated from the command line using ''uuid''.
$ uuid
ddeb27fb-d9a0-4624-be4d-4615062daed4
The default is to generate version 4 UUIDS, however the other versions are supported. Type ''uuid --help'' for details:
$ uuid --help
Usage:
uuid
uuid v1
uuid v3
uuid v4
uuid v5
uuid --help
Note: may be "URL" or "DNS" to use the corresponding UUIDs
defined by RFC4122
===== ECMAScript Modules =====
This library comes with [[https://www.ecma-international.org/ecma-262/6.0/#sec-modules|ECMAScript Modules]] (ESM) support for Node.js versions that support it ([[https://github.com/uuidjs/uuid/blob/HEAD/examples/node-esmodules/|example]]) as well as bundlers like [[https://rollupjs.org/guide/en/#tree-shaking|rollup.js]] ([[https://github.com/uuidjs/uuid/blob/HEAD/examples/browser-rollup/|example]]) and [[https://webpack.js.org/guides/tree-shaking/|webpack]] ([[https://github.com/uuidjs/uuid/blob/HEAD/examples/browser-webpack/|example]]) (targeting both, Node.js and browser environments).
import { v4 as uuidv4 } from 'uuid';
uuidv4(); // ⇨ '1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed'
To run the examples you must first create a dist build of this library in the module root:
npm run build
===== CDN Builds =====
==== ECMAScript Modules ====
To load this module directly into modern browsers that [[https://caniuse.com/#feat=es6-module|support loading ECMAScript Modules]] you can make use of [[https://jspm.org/|jspm]]:
==== UMD ====
To load this module directly into older browsers you can use the [[https://github.com/umdjs/umd|UMD (Universal Module Definition)]] builds from any of the following CDNs:
**Using [[https://unpkg.com/uuid@latest/dist/umd/|UNPKG]]**:
**Using [[https://cdn.jsdelivr.net/npm/uuid@latest/dist/umd/|jsDelivr]]**:
**Using [[https://cdnjs.com/libraries/uuid|cdnjs]]**:
These CDNs all provide the same ''[[#uuidv4options-buffer-offset|uuidv4()]]'' method:
Methods for the other algorithms (''[[#uuidv1options-buffer-offset|uuidv1()]]'', ''[[#uuidv3name-namespace-buffer-offset|uuidv3()]]'' and ''[[#uuidv5name-namespace-buffer-offset|uuidv5()]]'') are available from the files ''uuidv1.min.js'', ''uuidv3.min.js'' and ''uuidv5.min.js'' respectively.
===== "getRandomValues() not supported" =====
This error occurs in environments where the standard ''[[https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues|crypto.getRandomValues()]]'' API is not supported. This issue can be resolved by adding an appropriate polyfill:
==== React Native / Expo ====
- Install ''[[https://github.com/LinusU/react-native-get-random-values#readme|react-native-get-random-values]]''
- Import it before ''uuid''. Since ''uuid'' might also appear as a transitive dependency of some other imports it's safest to just import ''react-native-get-random-values'' as the very first thing in your entry point:
import 'react-native-get-random-values';
import { v4 as uuidv4 } from 'uuid';
Note: If you are using Expo, you must be using at least ''react-native-get-random-values@1.5.0'' and ''expo@39.0.0''.
==== Web Workers / Service Workers (Edge <= 18) ====
[[https://caniuse.com/#feat=cryptography|In Edge <= 18, Web Crypto is not supported in Web Workers or Service Workers]] and we are not aware of a polyfill (let us know if you find one, please).
===== Upgrading From uuid@7.x =====
==== Only Named Exports Supported When Using with Node.js ESM ====
''uuid@7.x'' did not come with native ECMAScript Module (ESM) support for Node.js. Importing it in Node.js ESM consequently imported the CommonJS source with a default export. This library now comes with true Node.js ESM support and only provides named exports.
Instead of doing:
import uuid from 'uuid';
uuid.v4();
you will now have to use the named exports:
import { v4 as uuidv4 } from 'uuid';
uuidv4();
==== Deep Requires No Longer Supported ====
Deep requires like ''require%%('%%uuid/v4')'' [[#deep-requires-now-deprecated|which have been deprecated in ]]''[[#deep-requires-now-deprecated|uuid@7.x]]'' are no longer supported.
===== Upgrading From uuid@3.x =====
"Wait... what happened to ''uuid@4.x'' - ''uuid@6.x''?!?"
In order to avoid confusion with RFC [[#uuidv4options-buffer-offset|version 4]] and [[#uuidv5name-namespace-buffer-offset|version 5]] UUIDs, and a possible [[http://gh.peabody.io/uuidv6/|version 6]], releases 4 thru 6 of this module have been skipped.
==== Deep Requires Now Deprecated ====
''uuid@3.x'' encouraged the use of deep requires to minimize the bundle size of browser builds:
const uuidv4 = require('uuid/v4'); // <== NOW DEPRECATED!
uuidv4();
As of ''uuid@7.x'' this library now provides ECMAScript modules builds, which allow packagers like Webpack and Rollup to do "tree-shaking" to remove dead code. Instead, use the ''import'' syntax:
import { v4 as uuidv4 } from 'uuid';
uuidv4();
... or for CommonJS:
const { v4: uuidv4 } = require('uuid');
uuidv4();
==== Default Export Removed ====
''uuid@3.x'' was exporting the Version 4 UUID method as a default export:
const uuid = require('uuid'); // <== REMOVED!
This usage pattern was already discouraged in ''uuid@3.x'' and has been removed in ''uuid@7.x''.
----
Markdown generated from [[https://github.com/uuidjs/uuid/blob/HEAD/README_js.md|README_js.md]] by [[https://github.com/broofa/runmd|{{https://camo.githubusercontent.com/9468a34345e7bbd42bae704e491c3b286542aa80d1bcf33dd3cd7801e0de4f7e/687474703a2f2f692e696d6775722e636f6d2f68304656797a552e706e67|RunMD Logo}}]]