limit-long-syntax.js 1.0 KB

1234567891011121314151617181920212223242526272829303132333435
  1. 'use strict';
  2. // This is an example of using tokens to add a custom behaviour.
  3. //
  4. // Require the use of `=` for long options and values by blocking
  5. // the use of space separated values.
  6. // So allow `--foo=bar`, and not allow `--foo bar`.
  7. //
  8. // Note: this is not a common behaviour, most CLIs allow both forms.
  9. // 1. const { parseArgs } = require('node:util'); // from node
  10. // 2. const { parseArgs } = require('@pkgjs/parseargs'); // from package
  11. const { parseArgs } = require('..'); // in repo
  12. const options = {
  13. file: { short: 'f', type: 'string' },
  14. log: { type: 'string' },
  15. };
  16. const { values, tokens } = parseArgs({ options, tokens: true });
  17. const badToken = tokens.find((token) => token.kind === 'option' &&
  18. token.value != null &&
  19. token.rawName.startsWith('--') &&
  20. !token.inlineValue
  21. );
  22. if (badToken) {
  23. throw new Error(`Option value for '${badToken.rawName}' must be inline, like '${badToken.rawName}=VALUE'`);
  24. }
  25. console.log(values);
  26. // Try the following:
  27. // node limit-long-syntax.js -f FILE --log=LOG
  28. // node limit-long-syntax.js --file FILE