电速宝智配引擎
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.

nanoid.js 1.5KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. #!/usr/bin/env node
  2. import { readFileSync } from 'node:fs'
  3. import { dirname, join } from 'node:path'
  4. import { fileURLToPath } from 'node:url'
  5. import { customAlphabet, nanoid } from '../index.js'
  6. function print(msg) {
  7. process.stdout.write(msg + '\n')
  8. }
  9. function error(msg) {
  10. process.stderr.write(msg + '\n')
  11. process.exit(1)
  12. }
  13. if (process.argv.includes('--version') || process.argv.includes('-v')) {
  14. let root = dirname(fileURLToPath(import.meta.url))
  15. let pkg = JSON.parse(readFileSync(join(root, '..', 'package.json'), 'utf8'))
  16. print(pkg.version)
  17. process.exit()
  18. }
  19. if (process.argv.includes('--help') || process.argv.includes('-h')) {
  20. print(`Usage
  21. $ nanoid [options]
  22. Options
  23. -s, --size Generated ID size
  24. -a, --alphabet Alphabet to use
  25. -v, --version Show version number
  26. -h, --help Show this help
  27. Examples
  28. $ nanoid -s 15
  29. S9sBF77U6sDB8Yg
  30. $ nanoid --size 10 --alphabet abc
  31. bcabababca`)
  32. process.exit()
  33. }
  34. let alphabet, size
  35. for (let i = 2; i < process.argv.length; i++) {
  36. let arg = process.argv[i]
  37. if (arg === '--size' || arg === '-s') {
  38. size = Number(process.argv[i + 1])
  39. i += 1
  40. if (Number.isNaN(size) || size <= 0) {
  41. error('Size must be positive integer')
  42. }
  43. } else if (arg === '--alphabet' || arg === '-a') {
  44. alphabet = process.argv[i + 1]
  45. i += 1
  46. } else {
  47. error('Unknown argument ' + arg)
  48. }
  49. }
  50. if (alphabet) {
  51. let customNanoid = customAlphabet(alphabet, size)
  52. print(customNanoid())
  53. } else {
  54. print(nanoid(size))
  55. }