negate.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. 'use strict';
  2. // This example is used in the documentation.
  3. // How might I add my own support for --no-foo?
  4. // 1. const { parseArgs } = require('node:util'); // from node
  5. // 2. const { parseArgs } = require('@pkgjs/parseargs'); // from package
  6. const { parseArgs } = require('..'); // in repo
  7. const options = {
  8. 'color': { type: 'boolean' },
  9. 'no-color': { type: 'boolean' },
  10. 'logfile': { type: 'string' },
  11. 'no-logfile': { type: 'boolean' },
  12. };
  13. const { values, tokens } = parseArgs({ options, tokens: true });
  14. // Reprocess the option tokens and overwrite the returned values.
  15. tokens
  16. .filter((token) => token.kind === 'option')
  17. .forEach((token) => {
  18. if (token.name.startsWith('no-')) {
  19. // Store foo:false for --no-foo
  20. const positiveName = token.name.slice(3);
  21. values[positiveName] = false;
  22. delete values[token.name];
  23. } else {
  24. // Resave value so last one wins if both --foo and --no-foo.
  25. values[token.name] = token.value ?? true;
  26. }
  27. });
  28. const color = values.color;
  29. const logfile = values.logfile ?? 'default.log';
  30. console.log({ logfile, color });
  31. // Try the following:
  32. // node negate.js
  33. // node negate.js --no-logfile --no-color
  34. // negate.js --logfile=test.log --color
  35. // node negate.js --no-logfile --logfile=test.log --color --no-color