Generates cryptographically strong, pseudo-random UIDs with custom size and base-encoding. Generated UIDs are strings that are guaranteed to always be the same length depending on the specified bit-size.
Great for generating things like compact API keys and UIDs that are safe to use in URLs and cookies.
Tip: The main benefit of this module is the ability to easily generate human-safe UIDs (using base58) and large UIDs that are more compact (using something like base94). If you’re just looking to generate URL-safe base64 IDs, the best package for that is uid-safe.
An optional callback that will be called with the results of generating the UID. If not specified, the function will return a promise.
Returns: ?Promise<string> - A promise that will resolve with the UID or reject with an error. Returns nothing if the cb parameter is specified.
async/await Example
const uidgen = new UIDGenerator();// This must be inside an async functionconst uid = await uidgen.generate();
Promise Example
const uidgen = new UIDGenerator();uidgen.generate() .then(uid => { // Use uid here });
Callback Example
const uidgen = new UIDGenerator();uidgen.generate((err, uid) => { if (err) throw err; // Use uid here});
uidgen.generateSync() ⇒ string
Synchronously generates a UID.
Returns: string - The generated UID.
Example
const uidgen = new UIDGenerator();const uid = uidgen.generateSync();
(readonly) uidgen.bitSize : number
The size of the UID that will be generated in bits (the bitSize value passed to the UIDGenerator constructor).
If the uidLength parameter is passed to the constructor instead of bitSize, bitSize is calculated as follows:
bitSize = Math.ceil(length * Math.log2(base));
Example
new UIDGenerator().bitSize // -> 128new UIDGenerator(256).bitSize // -> 256
(readonly) uidgen.uidLength : number
The length of the UID string that will be generated. The generated UID will always be this length.
This will be the same as the uidLength parameter passed to the UIDGenerator constructor.
If the uidLength parameter is not passed to the constructor, it will be calculated using the bitSize parameter as follows:
uidLength = Math.ceil(bitSize / Math.log2(base))
Example
new UIDGenerator().uidLength // -> 22new UIDGenerator(256, UIDGenerator.BASE62).uidLength // -> 43
(readonly) uidgen.baseEncoding : string
The set of characters used to encode the UID string (the baseEncoding value passed to the UIDGenerator constructor).