no-repeated-options.js 897 B

12345678910111213141516171819202122232425262728293031
  1. 'use strict';
  2. // This is an example of using tokens to add a custom behaviour.
  3. //
  4. // Throw an error if an option is used more than once.
  5. // 1. const { parseArgs } = require('node:util'); // from node
  6. // 2. const { parseArgs } = require('@pkgjs/parseargs'); // from package
  7. const { parseArgs } = require('..'); // in repo
  8. const options = {
  9. ding: { type: 'boolean', short: 'd' },
  10. beep: { type: 'boolean', short: 'b' }
  11. };
  12. const { values, tokens } = parseArgs({ options, tokens: true });
  13. const seenBefore = new Set();
  14. tokens.forEach((token) => {
  15. if (token.kind !== 'option') return;
  16. if (seenBefore.has(token.name)) {
  17. throw new Error(`option '${token.name}' used multiple times`);
  18. }
  19. seenBefore.add(token.name);
  20. });
  21. console.log(values);
  22. // Try the following:
  23. // node no-repeated-options --ding --beep
  24. // node no-repeated-options --beep -b
  25. // node no-repeated-options -ddd