3 * Copyright(c) 2014 Jonathan Ong
4 * Copyright(c) 2015-2017 Douglas Christopher Wilson
11 * Module dependencies.
15 var randomBytes = require('random-bytes')
22 var EQUAL_END_REGEXP = /=+$/
23 var PLUS_GLOBAL_REGEXP = /\+/g
24 var SLASH_GLOBAL_REGEXP = /\//g
32 module.exports.sync = uidSync
37 * @param {number} length
38 * @param {function} [callback]
43 function uid (length, callback) {
44 // validate callback is a function, if provided
45 if (callback !== undefined && typeof callback !== 'function') {
46 throw new TypeError('argument callback must be a function')
49 // require the callback without promises
50 if (!callback && !global.Promise) {
51 throw new TypeError('argument callback is required')
55 // classic callback style
56 return generateUid(length, callback)
59 return new Promise(function executor (resolve, reject) {
60 generateUid(length, function onUid (err, str) {
61 if (err) return reject(err)
68 * Create a unique ID sync.
70 * @param {number} length
75 function uidSync (length) {
76 return toString(randomBytes.sync(length))
80 * Generate a unique ID string.
82 * @param {number} length
83 * @param {function} callback
87 function generateUid (length, callback) {
88 randomBytes(length, function (err, buf) {
89 if (err) return callback(err)
90 callback(null, toString(buf))
95 * Change a Buffer into a string.
102 function toString (buf) {
103 return buf.toString('base64')
104 .replace(EQUAL_END_REGEXP, '')
105 .replace(PLUS_GLOBAL_REGEXP, '-')
106 .replace(SLASH_GLOBAL_REGEXP, '_')