nanoid.cjs 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. #!/usr/bin/env node
  2. let { nanoid, customAlphabet } = require('..')
  3. function print(msg) {
  4. process.stdout.write(msg + '\n')
  5. }
  6. function error(msg) {
  7. process.stderr.write(msg + '\n')
  8. process.exit(1)
  9. }
  10. if (process.argv.includes('--help') || process.argv.includes('-h')) {
  11. print(`
  12. Usage
  13. $ nanoid [options]
  14. Options
  15. -s, --size Generated ID size
  16. -a, --alphabet Alphabet to use
  17. -h, --help Show this help
  18. Examples
  19. $ nano --s 15
  20. S9sBF77U6sDB8Yg
  21. $ nano --size 10 --alphabet abc
  22. bcabababca`)
  23. process.exit()
  24. }
  25. let alphabet, size
  26. for (let i = 2; i < process.argv.length; i++) {
  27. let arg = process.argv[i]
  28. if (arg === '--size' || arg === '-s') {
  29. size = Number(process.argv[i + 1])
  30. i += 1
  31. if (Number.isNaN(size) || size <= 0) {
  32. error('Size must be positive integer')
  33. }
  34. } else if (arg === '--alphabet' || arg === '-a') {
  35. alphabet = process.argv[i + 1]
  36. i += 1
  37. } else {
  38. error('Unknown argument ' + arg)
  39. }
  40. }
  41. if (alphabet) {
  42. let customNanoid = customAlphabet(alphabet, size)
  43. print(customNanoid())
  44. } else {
  45. print(nanoid(size))
  46. }