You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

55 lines
1020 B

4 years ago
  1. /**
  2. * Module dependencies
  3. */
  4. var crypto = require('crypto');
  5. /**
  6. * 62 characters in the ascii range that can be used in URLs without special
  7. * encoding.
  8. */
  9. var UIDCHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  10. /**
  11. * Make a Buffer into a string ready for use in URLs
  12. *
  13. * @param {String}
  14. * @returns {String}
  15. * @api private
  16. */
  17. function tostr(bytes) {
  18. var chars, r, i;
  19. r = [];
  20. for (i = 0; i < bytes.length; i++) {
  21. r.push(UIDCHARS[bytes[i] % UIDCHARS.length]);
  22. }
  23. return r.join('');
  24. }
  25. /**
  26. * Generate an Unique Id
  27. *
  28. * @param {Number} length The number of chars of the uid
  29. * @param {Number} cb (optional) Callback for async uid generation
  30. * @api public
  31. */
  32. function uid(length, cb) {
  33. if (typeof cb === 'undefined') {
  34. return tostr(crypto.pseudoRandomBytes(length));
  35. } else {
  36. crypto.pseudoRandomBytes(length, function(err, bytes) {
  37. if (err) return cb(err);
  38. cb(null, tostr(bytes));
  39. })
  40. }
  41. }
  42. /**
  43. * Exports
  44. */
  45. module.exports = uid;