UNPKG

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