module uuid
The uuid module provides creation of unique ids. It can be used to generate UUID (Universally Unique Identifier) that meets various requirements
uuid
The module provides multiple static functions that can be used to configure and generate different kinds of UUIDs. The following is an example of using md5 to create a uuid:
1
2
3
4const uuid = require('uuid');
const ns = uuid.DNS;
const name = 'example.com';
console.log(uuid.md5(ns, name));
In the above example, the uuid module is first introduced, then the namespace and name are specified, and a UUID that meets the requirements is generated through the md5 algorithm and output to the console. Similarly, we can also use the snowflake algorithm to generate uuid. The following is an example of using the snowflake algorithm to create a uuid:
1
2
3const uuid = require('uuid');
const s = uuid.snowflake();
console.log(s);
In the above example, the snowflake() method returns aBufferObject, which can be converted to a string and output to the console to obtain the generated uuid.
static function
node
Create uuid using time and hostname
1static Buffer uuid.node();
Return results:
- Buffer, returns a generated binary id
md5
Create uuid using specifically named md5
1
2static Buffer uuid.md5(Integer ns,
String name);
Call parameters:
- ns: Integer, specifies the namespace, which can beuuid.DNS,uuid.URL,uuid.OID,uuid.X509
- name: String, specify name
Return results:
- Buffer, returns a generated binary id
random
Create uuid using random number
1static Buffer uuid.random();
Return results:
- Buffer, returns a generated binary id
sha1
Create uuid using specifically named sha1
1
2static Buffer uuid.sha1(Integer ns,
String name);
Call parameters:
- ns: Integer, specifies the namespace, which can beuuid.DNS,uuid.URL,uuid.OID,uuid.X509
- name: String, specify name
Return results:
- Buffer, returns a generated binary id
snowflake
Create uuid using Snowflake algorithm
1static Buffer uuid.snowflake();
Return results:
- Buffer, returns a generated binary id
static properties
hostID
Integer, query and modify the host id of the Snowflake algorithm
1static Integer uuid.hostID;
constant
DNS
md5 and sha1 specify name when creating uuid and name it as domain name
1const uuid.DNS = 0;
URL
md5 and sha1 specify name when creating uuid and name it asurladdress
1const uuid.URL = 1;
OID
md5 and sha1 specify name when creating uuid and name it as ISO OID
1const uuid.OID = 2;
X509
md5 and sha1 specify name when creating uuid and name it X.500 DN
1const uuid.X509 = 3;