UNPKG

17 kBMarkdownView Raw
1<!--
2 -- This file is auto-generated from README_js.md. Changes should be made there.
3 -->
4
5
6# uuid [![CI](https://github.com/uuidjs/uuid/workflows/CI/badge.svg)](https://github.com/uuidjs/uuid/actions?query=workflow%3ACI) [![Browser](https://github.com/uuidjs/uuid/workflows/Browser/badge.svg)](https://github.com/uuidjs/uuid/actions?query=workflow%3ABrowser)
7
8For the creation of [RFC4122](https://www.ietf.org/rfc/rfc4122.txt) UUIDs
9
10- **Complete** - Support for RFC4122 version 1, 3, 4, and 5 UUIDs
11- **Cross-platform** - Support for ...
12 - CommonJS, [ECMAScript Modules](#ecmascript-modules) and [CDN builds](#cdn-builds)
13 - NodeJS 12+ ([LTS releases](https://github.com/nodejs/Release))
14 - Chrome, Safari, Firefox, Edge browsers
15 - Webpack and rollup.js module bundlers
16 - [React Native / Expo](#react-native--expo)
17- **Secure** - Cryptographically-strong random values
18- **Small** - Zero-dependency, small footprint, plays nice with "tree shaking" packagers
19- **CLI** - Includes the [`uuid` command line](#command-line) utility
20
21> **Note** Upgrading from `uuid@3`? Your code is probably okay, but check out [Upgrading From `uuid@3`](#upgrading-from-uuid3) for details.
22
23> **Note** Only interested in creating a version 4 UUID? You might be able to use [`crypto.randomUUID()`](https://developer.mozilla.org/en-US/docs/Web/API/Crypto/randomUUID), eliminating the need to install this library.
24
25## Quickstart
26
27To create a random UUID...
28
29**1. Install**
30
31```shell
32npm install uuid
33```
34
35**2. Create a UUID** (ES6 module syntax)
36
37```javascript
38import { v4 as uuidv4 } from 'uuid';
39uuidv4(); // ⇨ '9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d'
40```
41
42... or using CommonJS syntax:
43
44```javascript
45const { v4: uuidv4 } = require('uuid');
46uuidv4(); // ⇨ '1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed'
47```
48
49For timestamp UUIDs, namespace UUIDs, and other options read on ...
50
51## API Summary
52
53| | | |
54| --- | --- | --- |
55| [`uuid.NIL`](#uuidnil) | The nil UUID string (all zeros) | New in `uuid@8.3` |
56| [`uuid.parse()`](#uuidparsestr) | Convert UUID string to array of bytes | New in `uuid@8.3` |
57| [`uuid.stringify()`](#uuidstringifyarr-offset) | Convert array of bytes to UUID string | New in `uuid@8.3` |
58| [`uuid.v1()`](#uuidv1options-buffer-offset) | Create a version 1 (timestamp) UUID | |
59| [`uuid.v3()`](#uuidv3name-namespace-buffer-offset) | Create a version 3 (namespace w/ MD5) UUID | |
60| [`uuid.v4()`](#uuidv4options-buffer-offset) | Create a version 4 (random) UUID | |
61| [`uuid.v5()`](#uuidv5name-namespace-buffer-offset) | Create a version 5 (namespace w/ SHA-1) UUID | |
62| [`uuid.validate()`](#uuidvalidatestr) | Test a string to see if it is a valid UUID | New in `uuid@8.3` |
63| [`uuid.version()`](#uuidversionstr) | Detect RFC version of a UUID | New in `uuid@8.3` |
64
65## API
66
67### uuid.NIL
68
69The nil UUID string (all zeros).
70
71Example:
72
73```javascript
74import { NIL as NIL_UUID } from 'uuid';
75
76NIL_UUID; // ⇨ '00000000-0000-0000-0000-000000000000'
77```
78
79### uuid.parse(str)
80
81Convert UUID string to array of bytes
82
83| | |
84| --------- | ---------------------------------------- |
85| `str` | A valid UUID `String` |
86| _returns_ | `Uint8Array[16]` |
87| _throws_ | `TypeError` if `str` is not a valid UUID |
88
89Note: Ordering of values in the byte arrays used by `parse()` and `stringify()` follows the left &Rarr; right order of hex-pairs in UUID strings. As shown in the example below.
90
91Example:
92
93```javascript
94import { parse as uuidParse } from 'uuid';
95
96// Parse a UUID
97const bytes = uuidParse('6ec0bd7f-11c0-43da-975e-2a8ad9ebae0b');
98
99// Convert to hex strings to show byte order (for documentation purposes)
100[...bytes].map((v) => v.toString(16).padStart(2, '0')); // ⇨
101 // [
102 // '6e', 'c0', 'bd', '7f',
103 // '11', 'c0', '43', 'da',
104 // '97', '5e', '2a', '8a',
105 // 'd9', 'eb', 'ae', '0b'
106 // ]
107```
108
109### uuid.stringify(arr[, offset])
110
111Convert array of bytes to UUID string
112
113| | |
114| -------------- | ---------------------------------------------------------------------------- |
115| `arr` | `Array`-like collection of 16 values (starting from `offset`) between 0-255. |
116| [`offset` = 0] | `Number` Starting index in the Array |
117| _returns_ | `String` |
118| _throws_ | `TypeError` if a valid UUID string cannot be generated |
119
120Note: Ordering of values in the byte arrays used by `parse()` and `stringify()` follows the left &Rarr; right order of hex-pairs in UUID strings. As shown in the example below.
121
122Example:
123
124```javascript
125import { stringify as uuidStringify } from 'uuid';
126
127const uuidBytes = [
128 0x6e, 0xc0, 0xbd, 0x7f, 0x11, 0xc0, 0x43, 0xda, 0x97, 0x5e, 0x2a, 0x8a, 0xd9, 0xeb, 0xae, 0x0b,
129];
130
131uuidStringify(uuidBytes); // ⇨ '6ec0bd7f-11c0-43da-975e-2a8ad9ebae0b'
132```
133
134### uuid.v1([options[, buffer[, offset]]])
135
136Create an RFC version 1 (timestamp) UUID
137
138| | |
139| --- | --- |
140| [`options`] | `Object` with one or more of the following properties: |
141| [`options.node` ] | RFC "node" field as an `Array[6]` of byte values (per 4.1.6) |
142| [`options.clockseq`] | RFC "clock sequence" as a `Number` between 0 - 0x3fff |
143| [`options.msecs`] | RFC "timestamp" field (`Number` of milliseconds, unix epoch) |
144| [`options.nsecs`] | RFC "timestamp" field (`Number` of nanoseconds to add to `msecs`, should be 0-10,000) |
145| [`options.random`] | `Array` of 16 random bytes (0-255) |
146| [`options.rng`] | Alternative to `options.random`, a `Function` that returns an `Array` of 16 random bytes (0-255) |
147| [`buffer`] | `Array \| Buffer` If specified, uuid will be written here in byte-form, starting at `offset` |
148| [`offset` = 0] | `Number` Index to start writing UUID bytes in `buffer` |
149| _returns_ | UUID `String` if no `buffer` is specified, otherwise returns `buffer` |
150| _throws_ | `Error` if more than 10M UUIDs/sec are requested |
151
152Note: The default [node id](https://tools.ietf.org/html/rfc4122#section-4.1.6) (the last 12 digits in the UUID) is generated once, randomly, on process startup, and then remains unchanged for the duration of the process.
153
154Note: `options.random` and `options.rng` are only meaningful on the very first call to `v1()`, where they may be passed to initialize the internal `node` and `clockseq` fields.
155
156Example:
157
158```javascript
159import { v1 as uuidv1 } from 'uuid';
160
161uuidv1(); // ⇨ '2c5ea4c0-4067-11e9-8bad-9b1deb4d3b7d'
162```
163
164Example using `options`:
165
166```javascript
167import { v1 as uuidv1 } from 'uuid';
168
169const v1options = {
170 node: [0x01, 0x23, 0x45, 0x67, 0x89, 0xab],
171 clockseq: 0x1234,
172 msecs: new Date('2011-11-01').getTime(),
173 nsecs: 5678,
174};
175uuidv1(v1options); // ⇨ '710b962e-041c-11e1-9234-0123456789ab'
176```
177
178### uuid.v3(name, namespace[, buffer[, offset]])
179
180Create an RFC version 3 (namespace w/ MD5) UUID
181
182API is identical to `v5()`, but uses "v3" instead.
183
184&#x26a0;&#xfe0f; Note: Per the RFC, "_If backward compatibility is not an issue, SHA-1 [Version 5] is preferred_."
185
186### uuid.v4([options[, buffer[, offset]]])
187
188Create an RFC version 4 (random) UUID
189
190| | |
191| --- | --- |
192| [`options`] | `Object` with one or more of the following properties: |
193| [`options.random`] | `Array` of 16 random bytes (0-255) |
194| [`options.rng`] | Alternative to `options.random`, a `Function` that returns an `Array` of 16 random bytes (0-255) |
195| [`buffer`] | `Array \| Buffer` If specified, uuid will be written here in byte-form, starting at `offset` |
196| [`offset` = 0] | `Number` Index to start writing UUID bytes in `buffer` |
197| _returns_ | UUID `String` if no `buffer` is specified, otherwise returns `buffer` |
198
199Example:
200
201```javascript
202import { v4 as uuidv4 } from 'uuid';
203
204uuidv4(); // ⇨ '1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed'
205```
206
207Example using predefined `random` values:
208
209```javascript
210import { v4 as uuidv4 } from 'uuid';
211
212const v4options = {
213 random: [
214 0x10, 0x91, 0x56, 0xbe, 0xc4, 0xfb, 0xc1, 0xea, 0x71, 0xb4, 0xef, 0xe1, 0x67, 0x1c, 0x58, 0x36,
215 ],
216};
217uuidv4(v4options); // ⇨ '109156be-c4fb-41ea-b1b4-efe1671c5836'
218```
219
220### uuid.v5(name, namespace[, buffer[, offset]])
221
222Create an RFC version 5 (namespace w/ SHA-1) UUID
223
224| | |
225| --- | --- |
226| `name` | `String \| Array` |
227| `namespace` | `String \| Array[16]` Namespace UUID |
228| [`buffer`] | `Array \| Buffer` If specified, uuid will be written here in byte-form, starting at `offset` |
229| [`offset` = 0] | `Number` Index to start writing UUID bytes in `buffer` |
230| _returns_ | UUID `String` if no `buffer` is specified, otherwise returns `buffer` |
231
232Note: The RFC `DNS` and `URL` namespaces are available as `v5.DNS` and `v5.URL`.
233
234Example with custom namespace:
235
236```javascript
237import { v5 as uuidv5 } from 'uuid';
238
239// Define a custom namespace. Readers, create your own using something like
240// https://www.uuidgenerator.net/
241const MY_NAMESPACE = '1b671a64-40d5-491e-99b0-da01ff1f3341';
242
243uuidv5('Hello, World!', MY_NAMESPACE); // ⇨ '630eb68f-e0fa-5ecc-887a-7c7a62614681'
244```
245
246Example with RFC `URL` namespace:
247
248```javascript
249import { v5 as uuidv5 } from 'uuid';
250
251uuidv5('https://www.w3.org/', uuidv5.URL); // ⇨ 'c106a26a-21bb-5538-8bf2-57095d1976c1'
252```
253
254### uuid.validate(str)
255
256Test a string to see if it is a valid UUID
257
258| | |
259| --------- | --------------------------------------------------- |
260| `str` | `String` to validate |
261| _returns_ | `true` if string is a valid UUID, `false` otherwise |
262
263Example:
264
265```javascript
266import { validate as uuidValidate } from 'uuid';
267
268uuidValidate('not a UUID'); // ⇨ false
269uuidValidate('6ec0bd7f-11c0-43da-975e-2a8ad9ebae0b'); // ⇨ true
270```
271
272Using `validate` and `version` together it is possible to do per-version validation, e.g. validate for only v4 UUIds.
273
274```javascript
275import { version as uuidVersion } from 'uuid';
276import { validate as uuidValidate } from 'uuid';
277
278function uuidValidateV4(uuid) {
279 return uuidValidate(uuid) && uuidVersion(uuid) === 4;
280}
281
282const v1Uuid = 'd9428888-122b-11e1-b85c-61cd3cbb3210';
283const v4Uuid = '109156be-c4fb-41ea-b1b4-efe1671c5836';
284
285uuidValidateV4(v4Uuid); // ⇨ true
286uuidValidateV4(v1Uuid); // ⇨ false
287```
288
289### uuid.version(str)
290
291Detect RFC version of a UUID
292
293| | |
294| --------- | ---------------------------------------- |
295| `str` | A valid UUID `String` |
296| _returns_ | `Number` The RFC version of the UUID |
297| _throws_ | `TypeError` if `str` is not a valid UUID |
298
299Example:
300
301```javascript
302import { version as uuidVersion } from 'uuid';
303
304uuidVersion('45637ec4-c85f-11ea-87d0-0242ac130003'); // ⇨ 1
305uuidVersion('6ec0bd7f-11c0-43da-975e-2a8ad9ebae0b'); // ⇨ 4
306```
307
308## Command Line
309
310UUIDs can be generated from the command line using `uuid`.
311
312```shell
313$ npx uuid
314ddeb27fb-d9a0-4624-be4d-4615062daed4
315```
316
317The default is to generate version 4 UUIDS, however the other versions are supported. Type `uuid --help` for details:
318
319```shell
320$ npx uuid --help
321
322Usage:
323 uuid
324 uuid v1
325 uuid v3 <name> <namespace uuid>
326 uuid v4
327 uuid v5 <name> <namespace uuid>
328 uuid --help
329
330Note: <namespace uuid> may be "URL" or "DNS" to use the corresponding UUIDs
331defined by RFC4122
332```
333
334## ECMAScript Modules
335
336This library comes with [ECMAScript Modules](https://www.ecma-international.org/ecma-262/6.0/#sec-modules) (ESM) support for Node.js versions that support it ([example](./examples/node-esmodules/)) as well as bundlers like [rollup.js](https://rollupjs.org/guide/en/#tree-shaking) ([example](./examples/browser-rollup/)) and [webpack](https://webpack.js.org/guides/tree-shaking/) ([example](./examples/browser-webpack/)) (targeting both, Node.js and browser environments).
337
338```javascript
339import { v4 as uuidv4 } from 'uuid';
340uuidv4(); // ⇨ '1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed'
341```
342
343To run the examples you must first create a dist build of this library in the module root:
344
345```shell
346npm run build
347```
348
349## CDN Builds
350
351### ECMAScript Modules
352
353To load this module directly into modern browsers that [support loading ECMAScript Modules](https://caniuse.com/#feat=es6-module) you can make use of [jspm](https://jspm.org/):
354
355```html
356<script type="module">
357 import { v4 as uuidv4 } from 'https://jspm.dev/uuid';
358 console.log(uuidv4()); // ⇨ '1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed'
359</script>
360```
361
362### UMD
363
364As of `uuid@9` [UMD (Universal Module Definition)](https://github.com/umdjs/umd) builds are no longer shipped with this library.
365
366If you need a UMD build of this library, use a bundler like Webpack or Rollup. Alternatively, refer to the documentation of [`uuid@8.3.2`](https://github.com/uuidjs/uuid/blob/v8.3.2/README.md#umd) which was the last version that shipped UMD builds.
367
368## Known issues
369
370### Duplicate UUIDs (Googlebot)
371
372This module may generate duplicate UUIDs when run in clients with _deterministic_ random number generators, such as [Googlebot crawlers](https://developers.google.com/search/docs/advanced/crawling/overview-google-crawlers). This can cause problems for apps that expect client-generated UUIDs to always be unique. Developers should be prepared for this and have a strategy for dealing with possible collisions, such as:
373
374- Check for duplicate UUIDs, fail gracefully
375- Disable write operations for Googlebot clients
376
377### "getRandomValues() not supported"
378
379This error occurs in environments where the standard [`crypto.getRandomValues()`](https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues) API is not supported. This issue can be resolved by adding an appropriate polyfill:
380
381### React Native / Expo
382
3831. Install [`react-native-get-random-values`](https://github.com/LinusU/react-native-get-random-values#readme)
3841. 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:
385
386```javascript
387import 'react-native-get-random-values';
388import { v4 as uuidv4 } from 'uuid';
389```
390
391Note: If you are using Expo, you must be using at least `react-native-get-random-values@1.5.0` and `expo@39.0.0`.
392
393### Web Workers / Service Workers (Edge <= 18)
394
395[In Edge <= 18, Web Crypto is not supported in Web Workers or Service Workers](https://caniuse.com/#feat=cryptography) and we are not aware of a polyfill (let us know if you find one, please).
396
397### IE 11 (Internet Explorer)
398
399Support for IE11 and other legacy browsers has been dropped as of `uuid@9`. If you need to support legacy browsers, you can always transpile the uuid module source yourself (e.g. using [Babel](https://babeljs.io/)).
400
401## Upgrading From `uuid@7`
402
403### Only Named Exports Supported When Using with Node.js ESM
404
405`uuid@7` 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.
406
407Instead of doing:
408
409```javascript
410import uuid from 'uuid';
411uuid.v4();
412```
413
414you will now have to use the named exports:
415
416```javascript
417import { v4 as uuidv4 } from 'uuid';
418uuidv4();
419```
420
421### Deep Requires No Longer Supported
422
423Deep requires like `require('uuid/v4')` [which have been deprecated in `uuid@7`](#deep-requires-now-deprecated) are no longer supported.
424
425## Upgrading From `uuid@3`
426
427"_Wait... what happened to `uuid@4` thru `uuid@6`?!?_"
428
429In order to avoid confusion with RFC [version 4](#uuidv4options-buffer-offset) and [version 5](#uuidv5name-namespace-buffer-offset) UUIDs, and a possible [version 6](http://gh.peabody.io/uuidv6/), releases 4 thru 6 of this module have been skipped.
430
431### Deep Requires Now Deprecated
432
433`uuid@3` encouraged the use of deep requires to minimize the bundle size of browser builds:
434
435```javascript
436const uuidv4 = require('uuid/v4'); // <== NOW DEPRECATED!
437uuidv4();
438```
439
440As of `uuid@7` 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:
441
442```javascript
443import { v4 as uuidv4 } from 'uuid';
444uuidv4();
445```
446
447... or for CommonJS:
448
449```javascript
450const { v4: uuidv4 } = require('uuid');
451uuidv4();
452```
453
454### Default Export Removed
455
456`uuid@3` was exporting the Version 4 UUID method as a default export:
457
458```javascript
459const uuid = require('uuid'); // <== REMOVED!
460```
461
462This usage pattern was already discouraged in `uuid@3` and has been removed in `uuid@7`.
463
464---
465
466Markdown generated from [README_js.md](README_js.md) by <a href="https://github.com/broofa/runmd"><image height="12px" src="https://camo.githubusercontent.com/5c7c603cd1e6a43370b0a5063d457e0dabb74cf317adc7baba183acb686ee8d0/687474703a2f2f692e696d6775722e636f6d2f634a4b6f3662552e706e67" /></a>