Coder Social home page Coder Social logo

75lb / command-line-args Goto Github PK

View Code? Open in Web Editor NEW
679.0 6.0 109.0 991 KB

A mature, feature-complete library to parse command-line options.

License: MIT License

JavaScript 100.00%
getopt argv option-parser npm-package nodejs-modules command-line-parser

command-line-args's Introduction

view on npm npm module downloads Gihub repo dependents Gihub package dependents Node.js CI Coverage Status js-standard-style

Upgraders, please read the release notes

command-line-args

A mature, feature-complete library to parse command-line options.

Synopsis

You can set options using the main notation standards (learn more). These commands are all equivalent, setting the same values:

$ example --verbose --timeout=1000 --src one.js --src two.js
$ example --verbose --timeout 1000 --src one.js two.js
$ example -vt 1000 --src one.js two.js
$ example -vt 1000 one.js two.js

To access the values, first create a list of option definitions describing the options your application accepts. The type property is a setter function (the value supplied is passed through this), giving you full control over the value received.

const optionDefinitions = [
  { name: 'verbose', alias: 'v', type: Boolean },
  { name: 'src', type: String, multiple: true, defaultOption: true },
  { name: 'timeout', alias: 't', type: Number }
]

Next, parse the options using commandLineArgs():

const commandLineArgs = require('command-line-args')
const options = commandLineArgs(optionDefinitions)

options now looks like this:

{
  src: [
    'one.js',
    'two.js'
  ],
  verbose: true,
  timeout: 1000
}

Advanced usage

Beside the above typical usage, you can configure command-line-args to accept more advanced syntax forms.

  • Command-based syntax (git style) in the form:

    $ executable <command> [options]
    

    For example.

    $ git commit --squash -m "This is my commit message"
    
  • Command and sub-command syntax (docker style) in the form:

    $ executable <command> [options] <sub-command> [options]
    

    For example.

    $ docker run --detached --image centos bash -c yum install -y httpd
    

Usage guide generation

A usage guide (typically printed when --help is set) can be generated using command-line-usage. See the examples below and read the documentation for instructions how to create them.

A typical usage guide example.

usage

The polymer-cli usage guide is a good real-life example.

usage

Further Reading

There is plenty more to learn, please see the wiki for examples and documentation.

Install

$ npm install command-line-args --save

© 2014-22 Lloyd Brookes <[email protected]>. Documented by jsdoc-to-markdown.

command-line-args's People

Contributors

75lb avatar joeferner avatar lirantal avatar mykmelez avatar n4m avatar rafaeleyng avatar sblackstone avatar stonecypher avatar zawataki avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

command-line-args's Issues

cli.parse() is not a function

I've installed command-line-args and compiled a basic code for passing arguments in cli to do a mongodb request. I get this error at runtime.

  var options = cli.parse()
                    ^
TypeError: cli.parse is not a function
    at commandLineOptions (C:\MCS-Node\MCS-Node\mongo.js:64:21)
    at Object.<anonymous> (C:\MCS-Node\MCS-Node\mongo.js:6:15)
    at Module._compile (module.js:409:26)
    at Object.Module._extensions..js (module.js:416:10)
    at Module.load (module.js:343:32)
    at Function.Module._load (module.js:300:12)
    at Function.Module.runMain (module.js:441:10)
    at startup (node.js:139:18)
    at node.js:968:3

Any help? ty

Node version: 4.4.7
NPM version: 3.10.5
Mongo version: 3.2.8
Windows 7 Pro

Incorrect value being parsed

For options with multiple: false and defaultOption: true, the first value parsed should be taken - not the last.

Say you have this option definition:

{ name: 'file', defaultOption:true }

And you run your example app this way:

$ example one.js two.js three.js

Then, in the output file should be set to 'one.js', not 'three.js' (as it is currently).

Consider dropping core-js dependency

core-js makes up the vast majority of the total install size of this package, it'd be really nice to remove it for projects that aren't already pulling it in. In some projects I maintain I've been asked to use another arg parser because of this.

The currently active LTS versions, 4 and 6, support all the ES6 features used here. Node 0.12 is still in maintenance, but only for two more weeks.

I'd be willing to submit a PR for this.

Incorrect UNKNOWN_OPTION getting thrown

Hi, I have a project where various files use your commandLineArgs lib. Generally speaking, it's great, and has proved super useful. However, I've run into a problem that is quite frustrating.
Here's the issue: scriptA has X command line args, and scriptB has Y command line args. But scriptA requires scriptB. Now we have a problem. When I do the following...

// flag1 is defined in scriptA, but not in scriptB
node scriptA  --flag1
->  `UNKNOWN_OPTION`

I get... UNKNOWN_OPTION. Which is pretty messed up. The args I'm passing to scriptA are assuredly defined and valid. But I'm getting an error because commandLineArgs thinks I'm passing flag1 to scriptB, which I'm not doing.

The order in which these are defined is irrelevant. My assumption now is that commandLineArgs checks for unknown params at definition time, though I don't know for sure.

It seems like commandLineArgs should be smart enough to separate this somehow. Maybe it tracks which file is defining which set of args and it could then, at run time, determine if the option is actually unknown for the file that's getting called. Or maybe it just concats all options getting defined within some global store, and it only cares about duplicate names within one "definition call".
My options for solving this are pretty lame. I either keep a global list of all options for all files, and require that, or maybe do a try catch (though unsure if that actually would work). But as a different issue alludes to, I can't just turn off the "Unknown option" error.

Thoughts? Thanks! Otherwise this lib is great.

Add option to disable multiple arguments with the form `-m a b`

If you have default options combined with multiple you cannot put the default options after the multiple argument.

Example

{name: 'group', alias: 'g', multiple: true},
{name: 'args', defaultOption: true, multiple: true}

When trying to parse -g group1 -g group2 a b, the results end up as group: ['group1', 'group2', 'a', 'b']. I would like to have it result in group: ['group1', 'group2'], args: ['a', 'b']

It would be nice to have an option to disable this type of multiple behavior

"description" missing in documentation

If you want to render cli.getUsage you can pass a description property to the options per item. This is not reflected in the documentation, but the usage example shows usage rendered with description.

just to let you know ... i really like that project, thanks for that 👍

Bash completion

If this is implemented, this would be a killer feature. I like the way the args can be declaratively described by the hash. From that hash it would be possible to create the bash completion script. If this script is added to /etc/bash_completion.d it can complete the allowed args when pressing TAB.

yargs has something like that, but it's low lvl api and user needs to implement it basically itself. But these bash completion scripts could be generated. Btw. this is very nice way to do that almost mechanically: https://github.com/kubernetes/kubernetes/blob/master/pkg/kubectl/cmd/completion.go
and the result is similar to this:
https://github.com/janetkuo/kubernetes/blob/b673920ccf83c9448398243ff5ea3afab989d5fc/contrib/completions/bash/kubectl

NAME_MISSING

When i run the code given in README.md for command-line-usage example, i get the following error

NAME_MISSING: Invalid option definitions: the name property is required on each definition

Boolean options with defaultOptions

With these definitions...
var optionDefinitions = [ { name: 'help', alias: 'h', type: Boolean }, { name: 'long', alias: 'l', type: Boolean }, { name: 'paths', alias: 'p', type: String, defaultOption: true } ];

and using the argv array...
var argv = ['-l', '/etc'];

Instead of getting { long: true, paths: 'etc' } the result is { long: 'etc' }

TypeError: def.isBoolean is not a function

Hey Im using node 6.3.0
When I ran the following command

$ node RecordingSourceOnly.js -t 5

where RecordingSourceOnly.js is

const commandLineArgs = require('command-line-args')

const optionDefinitions = [
    { name: 'verbose', alias: 'v', type: Boolean },
    { name: 'src', type: String, multiple: true, defaultOption: true },
    { name: 'timeout', alias: 't', type: Number }
]
const options = commandLineArgs(optionDefinitions)

I got

    if (def.isBoolean()) {
            ^

TypeError: def.isBoolean is not a function
    at Output.set (/Users/ron.yadgar/Documents/Repositories/liveDVR/node_modules/command-line-args/lib/output.js:67:13)
    at argv.forEach.arg (/Users/ron.yadgar/Documents/Repositories/liveDVR/node_modules/command-line-args/lib/command-line-args.js:50:27)
    at Argv.forEach (native)
    at commandLineArgs (/Users/ron.yadgar/Documents/Repositories/liveDVR/node_modules/command-line-args/lib/command-line-args.js:48:8)
    at Object.<anonymous> (/Users/ron.yadgar/Documents/Repositories/liveDVR/lib/recording/RecordingSourceOnly.js:32:17)
    at Module._compile (module.js:541:32)
    at Object.Module._extensions..js (module.js:550:10)
    at Module.load (module.js:458:32)
    at tryModuleLoad (module.js:417:12)
    at Function.Module._load (module.js:409:3)

defaultValue for type Array null

Fails to parse command line if defaultValue is null and type is String and multiple is true.

Using following options:

    {
        name: 'tags',
        alias: 't',
        type: String,
        multiple: true,
        defaultValue: null
    },

If --tags array values are provided in CLI then it parses them incorrectly. Last string is split in array of chars and everything else is ignored.

Halfway point for mutiple: true ?

I've got code where I want to specify multiple of an option, but I don't want the parser to be "greedy".
eg:

var CLA  = require('command-line-args');
var cli = CLA([
    { name: 'mech', alias: 'm', type: String,  multiple: true },
    { name: 'source',    alias: 's', type: FileDetails,  defaultOption: true },
]);
console.error(cli.parse());

node lib/main.js -m one -m two somefile.taco
would yield an options of

{  mech: [ "one", "two" ],
    src: { filename: "somefile.taco", exists: true } }

instead of

{ mech: [ "one", "two", "somefile.taco" ] }

Ideally such a mechanism would allow an accumulator for options that don't have arguments.
Such as allowing me to set the debug value to 3 by specifying -d multiple times.
eg:
node lib/main.js -d -d -d -m one -m two somefile.taco
having potentially the output of:

{ debug: 3, 
  mech: [ "one", "two" ],
  src: { filename: "somefile.taco", exists: true } }

(My experiments in writing a function ala FileDetails didn't go too well.)

This might also require an additional flag that indicates an arg doesn't take any value and is only a key.

Parsing arguments in Node script

First off, thanks for putting together such an awesome module! This is exactly the tool I need, just one minor thing I can't seem to figure out: How do I parse the command line arguments in a script?

For example
In my package.json I have the following

"scripts": {
    "start": "node ./bin/www"
  }

and in the www script I call

var commandLineArgs = require('command-line-args');

var cli = commandLineArgs([ 
  { name: "port", alias: "p", type: String, defaultValue: 4000 }
]);

var options = cli.parse();
console.log("Options: ", options);
console.log("Argv: ", process.argv);

If I then call npm start --port 2828 the default value of 4000 gets set; however, no matter what I do, the options object never parses the value passed in from the command line. If I inspect the process.argv Array, I can see that the value I passed in (2828) is in fact listed, but it doesn't seem to get picked up by cli.parse(). I also tried manually passing the process.argv array into the cli.parse method, but that had no impact.

Do you have any pointers on what I might need to do to get this up and running?

Thanks in advance!

CHANGELOG

hi there, I just want to point out that you need to add a CHANGELOG file so people can see what change and what doesn't..

I was killing my brain why .parse doesn't work.just to realize that it was in a older version.

thanks :)

Arguments containing newlines are parsing incorrectly

Thanks for a great library!

Suppose invoke my script on bash as follows (typing my newlines directly):

$ npm run my-script -- --arg="foo
bar 
wibble"

I end up with arg="foo".

However bash seems to support this in general, suppose I do:

$ echo "foo
bar
wibble"

I see:

foo
bar
wibble

Allow unknown cli arguments

I have this case in which I don't know all the cli arguments. It would be nice if there was an options to disable the unknown option check.

uglify error

ERROR in client.js from UglifyJs
Unexpected token: name (ArgRegExp) [./node_modules/command-line-args/lib/option.js:3,0][client.js:14207,6]

Negative number as argument throws error "Invalid option"

If I try to parse a flag with a negative value like --one="-1" the parser throws the following error:

[Error: Invalid option: -1]

You can test this by extending the type-number.js tests with:

t.deepEqual(
  cliArgs(optionDefinitions).parse([ '--one', '-1' ]),
  { one: -1 }
)

Cannot find module 'babel/polyfill'

Hi,

I have the following source:

  "use strict";

  let fs = require('readdirp'),
      es = require('event-stream'),
      commandLineArgs = require("command-line-args");


  let cli = commandLineArgs([
      { name: "verbose", alias: "v", type: Boolean },
      { name: "src", type: String, multiple: true, defaultOption: true },
      { name: "timeout", alias: "t", type: Number }
  ]);

  let options = cli.parse();

When running this with iojs i get the following error:

  Error: Cannot find module 'babel/polyfill'
      at Function.Module._resolveFilename (module.js:336:15)
      at Function.Module._load (module.js:286:25)
      at Module.require (module.js:365:17)
      at require (module.js:384:17)
      at Object.<anonymous> (xxxxxxx/node_modules/command-line-args/es5/command-line-args.js:7:1)
      at Module._compile (module.js:430:26)
      at Object.Module._extensions..js (module.js:448:10)
      at Module.load (module.js:355:32)
      at Function.Module._load (module.js:310:12)
      at Module.require (module.js:365:17)

Node (iojs) and npm versions:

➜  node -v
v3.0.0
➜  npm -v
2.13.3

best,
Stefan

Reverse decision to guarantee a multiple returns an array

In the current release (v4.0.4), an option defined with multiple: true is guaranteed to return an array whether the option is set or not. This differs from v4.0.3 which only returned an array if the option was set, returning undefined otherwise.

Take this example:

const options = commandLineArgs({ name: 'something', multiple: true })

In v4.0.4, if the --something option is not set the options.something value will be []. In v4.0.3 the value will be undefined.

Guaranteeing a multiple returns an array makes life easier for the user who no longer has to test whether the value is an array before using methods like .forEach on it. However, this change in behaviour broke Object.assign behaviour.

const options = commandLineArgs({ name: 'something', multiple: true })
const mergedOptions = Object.assign({ something: [ 'car' ], options }

In the above example, if the --something option is not set, mergedOptions.something will equal [] in v4.0.4 and [ 'car' ] in v4.0.3. This oversight meant v4.0.4 introduced a breaking change for users of Object.assign, therefore the previous behaviour must be returned.

definitions.load is not a function

Here's my setup:

const commandLineArgs = require('command-line-args')

const clargsDefinitions = [
	{ name: 'reduxLogger', alias: 'r', type: Boolean, defaultOption: false },
]

const options = commandLineArgs(clargsDefinitions)

export default options

Here's the error:

TypeError: definitions.load is not a function
      
      at commandLineArgs (node_modules/command-line-args/lib/command-line-args.js:37:15)
      at Object.<anonymous> (config/clargs.js:9:15)
      at Object.<anonymous> (app/store.js:11:41)
      at Object.<anonymous> (tests/Store.test.js:1:409)
      at handle (node_modules/worker-farm/lib/child/index.js:41:8)
      at process.<anonymous> (node_modules/worker-farm/lib/child/index.js:47:3)
      at emitTwo (events.js:106:13)
      at process.emit (events.js:191:7)
      at process.nextTick (internal/child_process.js:744:12)
      at _combinedTickCallback (internal/process/next_tick.js:67:7)
      at process._tickCallback (internal/process/next_tick.js:98:9)

Simultaneously use of defaultValue and defaultOption not possible ?

Just run into this, maybe I am just missing something in the docs.

I want to have a default option, which has a default value as fallback. When I call it with the correct argument name example --path ./whatever it parses the value, as intended. But If I call it like a defaultOption via example ./whatever it ignores the set value and loads the defaultValue.

My code looks like this

const commandLineArgs = require('command-line-args')
const optionDefinitions = [
  { name: 'path', type: String, defaultOption: true, defaultValue: './' },
]
const options = commandLineArgs(optionDefinitions)

console.log(options)

Cheers 😃

defaultValues that are falsey are not maintained

To reproduce create a list of options where one has a defaultValue of false, and another of any non-empty string (such as "true"). Run the resulting application with no arguments.

Note that only the string defaulted argument is present.

add option to return output properties in camel case

Add option to return camel-case property names on the output object, e.g.

const commandLineArgs = require('./')
const optionDefinitions = [
  { name: 'option-one' }
]

const options = commandLineArgs(optionDefinitions, { camelCase: true })
console.log(options)

/*
returns:

{  optionOne: 'something' }

instead of : 

{  'option-one': 'something' }
*/

(minor) Underlining does not work on Windows

Bold, however, does.

Consider the following usage rule:

{
  "title": "immaterial",
  "description": "Converts Material-JSON to Material-SASS, react/angular imperative",
  "synopsis": [
    "$ immaterial mytheme.json",
    "$ immaterial mytheme.json [[bold]{--output} [underline]{theme}] [[bold]{--verbose}] [[bold]{--silent}] [[bold]{--explicit}]",
    "$ immaterial mytheme.json [[bold]{-vse12345}] [[bold]{-o} [[underline]{theme}]]",
    "$ immaterial --help"
  ],
  "footer": "Project home: [underline]{https://github.com/StoneCypher/immaterial/}"
}

This renders as follows on Windows:
immaterial help no underscore

I assume this is a result of your console formatter.

Some console formatters do give underlines correctly on Windows, such as https://www.npmjs.com/package/cli-color.

This probably isn't that big a deal. Just noting it for posterity.

Weird error as soon as I require library

Call stack, entry point from my code: easy-coveralls/server.js:11:25

const commandLineArgs = require('command-line-args')

So it fails as soon as I require it!?

/Users/kristianmandrup/repos/node-libs/easy-coveralls/node_modules/command-line-args/lib/command-line-args.js Error
  at new JS_Parse_Error (<anonymous>:1545:18)
  ...
  at Instrument.process (/Users/kristianmandrup/repos/node-libs/easy-coveralls/node_modules/jscoverage/lib/instrument.js:61:22)
  at Object.exports.process (/Users/kristianmandrup/repos/node-libs/easy-coveralls/node_modules/jscoverage/lib/jscoverage.js:133:18)
  at Object.Module._extensions..js (/Users/kristianmandrup/repos/node-libs/easy-coveralls/node_modules/jscoverage/lib/patch.js:106:28)
  at Module.require (/Users/kristianmandrup/repos/node-libs/easy-coveralls/node_modules/jscoverage/lib/patch.js:76:30)
  at require (internal/module.js:20:19)
  at Object.<anonymous> (/Users/kristianmandrup/repos/node-libs/easy-coveralls/node_modules/command-line-args/index.js:61:22)
  at Module._compile (module.js:573:32)
  at Object.Module._extensions..js (/Users/kristianmandrup/repos/node-libs/easy-coveralls/node_modules/jscoverage/lib/patch.js:115:12)
  at Module.require (/Users/kristianmandrup/repos/node-libs/easy-coveralls/node_modules/jscoverage/lib/patch.js:76:30)
  at require (internal/module.js:20:19)
  at Object.<anonymous> (/Users/kristianmandrup/repos/node-libs/easy-coveralls/server.js:11:25)

todo list

  • factor out getOptionValueSet
  • option to pass whole multiple:true array output to a function/constructor
  • usage
    • customise column widths
  • _discarded property for unclaimed values
  • permit arbitrary, un-defined options, and group them

Throw error if unexpected option values are present

The docs say By default, an exception is thrown if the user sets an unknown option (one without a valid definition). But as mentioned in #39, if your definition is { name: 'file', defaultOption:true } and command line is $ example one.js two.js three.js, file will be set to one.js.

But it should throw an error by default, because it means I've specified things on the command line that weren't expected, so I should either correct the command line or the definition rather than letting the program carry on because something could be wrong.

Not allowing use of full name alias with `defaultOption` arg

I am wanting to have:

const optionDefinitions = [
    ...
    { name: 'script', type: String, defaultOption: true }
];

Currently that allows the user to use:

mymodule index.js

# or 

mymodule --script index.js

I don't want to allow the user to input the second option.

Any ideas on how I would do this or if it is/can be supported?

Equals (=) in argument throws "Invalid option"

Hi,

Thanks for this great lib!

However I can't use argument values such as --url="my-url?q=123" since the regex for parsing x=y arguments doesn't seem to be checking for quotes, which means my equal sign in the value will break it.

I believe this is a similar issue: #10

lib/output2.js: 'this' is not allowed before super()

I need to transpile my application for an earlier version of node, but babel throws an error because not calling super in a subclass is not es6 compliant.

SyntaxError: E:/projects/Biborg/microserver/temp/node_modules/command-line-args/lib/output2.js: 'this' is not allowed before super()
  18 | class Output extends Map {
  19 |   constructor (definitions) {
> 20 |     this.definitions = definitions
     |     ^
  21 |   }

babel, babel-preset-es2015

using command-line-usage to print command-line-args definitions

In your readme you say that command-line-usage can be used to generate a guide to using the tools. But it does not have an example of how to do that.

I naively tried to do the following

const commandLineArgs = require('command-line-args');
const getUsage = require('command-line-usage')

const optionDefinitions = [
  { name: 'site', type: String, defaultValue: 'local', description: 'The site we want to test, by default it will be testing on your local host. Values are business, help, or local.'},
  { name: 'testTarget', type: String, defaultValue: 'pages', description: 'Values are either business or integration. In localhost it is assumed that pages are production, and components are integration' },
  { name: 'debug',  type: Number, defaultValue: 2, description: 'Passes value to phantomflow to control debugging - A value of 1 will output more logging, 2 will generate full page screenshots per test which can be found in the test-results folder. Forces tests onto one thread for readability. ' },
  { name: 'createReport', type: Boolean, defaultValue: false, description: 'Passes value to phantomflow as to whether there should be any report created' },
  { name: 'remoteDebug', type: Boolean, defaultValue: true, description: 'Enable PhantomJS remote debugging' },
  { name: 'help', alias: 'h', type: Boolean, defaultValue: false, description: 'Show this help message' },
  { name: 'dashboard', type: Boolean, defaultValue: false, description: 'Allow dashboard creation and display in command line' }
  
  
]
const options = commandLineArgs(optionDefinitions);
const usage = getUsage(optionDefinitions);
console.log(usage);

expecting that I would get some sort of legible report out, but I just get about 5 empty lines in my console. This is on Windows 10, latest version.

I realize that the examples in the command-line-usage tool are quite different than yours, but I expected that if the guide says that command-line-usage can be used that there was someway of handling the command-line-args structure gracefully?

Not sure how to send a value which starts with "--"

I am writing a tool which has an option to pass flags for one of the CLI tools it invokes. I assumed an invocation like this would work:

tattoo --wct-flags="--local firefox"

Unfortunately, command-line-args thinks I'm passing in 2 args. --wct-flags and --local which makes it sad at me.

Is there a way right now, that I'm not seeing, to pass a value that has a - prefix without command-line-args interpreting it as an option to parse?

cannot generate simple usage string after recent refactoring

After you've refactored out command-line-usage there's no way I can generate simple usage string out of list of [ { name: 'first' }, { name: 'second' } ] etc. option definitions. This breaks existing apps. One needs to carefully go through the docs.

My old code:

    opts = cliArgs([
    {
      name: 'dry_run',
      alias: 'n',
      type: Boolean
    },
    {
      name: 'help',
      alias: 'h',
      type: Boolean
    }]);
    console.log(opts.getUsage());

Needs to get extra wrapping to:

    defs = [
    {
      name: 'dry_run',
      alias: 'n',
      type: Boolean
    },
    {
      name: 'help',
      alias: 'h',
      type: Boolean
    }]
    opts = cliArgs(defs);
    console.log(getUsage({
      header: 'Options',
      optionList: opts_definitions
    }));

This could be clearer stated in docs when you mention command-line-usage.

buggy handling of unknown options with partial: true, but also default option with multiple: true

Consider the following test code:

const args = require('command-line-args');
const optionDefs = [ { name: 'stringList', type: String, multiple: true, defaultOption: true } ];
const options = args(optionDefs, { partial: true });
console.log(JSON.stringify(options));
options.stringList.forEach((item) => { console.log("got list item: '" + item + "'"); });

If you run this code with the following syntax:
node test.js item1 item2 --unknownOpt=item3

I would expect the following output:

{"stringList":["item1","item2"],"_unknown":["--unknownOpt","item3"]}
got list item: 'item1'
got list item: 'item2'

But instead, you get this:

{"stringList":["item1","item2","item3"],"_unknown":["--unknownOpt"]}
got list item: 'item1'
got list item: 'item2'
got list item: 'item3'

As you can see, even though 'item3' is specified with an equal sign after --unknownOpt, the value still gets included in the defaultOption stringList.

UNKNOWN_OPTION could be optional

When I use an app that uses the npm module with mocha (and I want to pass some options to mocha and others to the module being tested), I see an UNKNOWN_OPTION error. For example, I want to pass --no-timeout to mocha.

Error when used with cluster

First, think you for this great tool.

I am having an issue with using it with node cluster module. Here is a simple script to reproduce it:

var cluster = require("cluster");
var commandLineArgs = require('command-line-args');
var cli = commandLineArgs([{ name: 'config', type: String }]);

//var options = cli.parse(process.argv); // works fine
var options = cli.parse(); // "Cannot find module undefine" error

if (cluster.isMaster) {
    cluster.fork();  // fork one worker
} else {
    console.log('worker');
}

If I run cli.parse(process.argv), it works fine. With cli.parse(), I am getting following error from worker process:

Cannot find module '/Users/xxx/Documents/debug/undefined'
    at Function.Module._resolveFilename (module.js:336:15)
    at Function.Module._load (module.js:278:25)
    at Function.Module.runMain (module.js:501:10)
    at startup (node.js:129:16)
    at node.js:814:3

I am running node 0.12.5 on Darwin Kernel Version 13.4.0

Thanks in advance!

Catching "invalid option"

Hi,

what's the best way you recommend to catch the "invalid option" problem, so if the user sets a parameter wrongly or uses a parameter which is not defined?

Beside that:
I think an option would be great to suppress this behavior, so any undefined parameter would just be ignored and no exception would be thrown.

Regards
Stefan

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.