1

So I'm struggling with passing command line option arguments from npm to a node script. I can pass options themselves, but not as key value pairs.

For my package.json I have:

"scripts": {
   "test": ". ./.env; node app.js --"
 },

(my understanding is that for npm you need to include and extra "--" to pass arguments) and in my app.js I have:

const { argv, options } = require('yargs');
console.log(argv._);

When I run

$ npm run test FOO BAR

I get:

[ 'FOO', 'BAR' ]

great, that worked, but if I try

$ npm run test FOO --BAR 99RedBalloons

I get:

[ 'FOO', '99RedBallons' ]

and

$ npm run test FOO --BAR=99RedBallons gives me:

[ 'FOO' ]

Wha? So, my question really is, using "run npm <>" and I assume yargs (since I believe that is the most popular package), how can I arrive with a arg._ of ["FOO", "Bar" : "99RedBalloons"].

Thanks!

4
  • Did you try npm run test FOO Bar 99RedBallons? Commented Nov 6, 2018 at 15:38
  • I have, and that gives me [ 'FOO', 'Bar', '99RedBalloons' ] Commented Nov 6, 2018 at 16:16
  • There something weird to me how npm is passing command line arguments to the node script Commented Nov 6, 2018 at 16:17
  • I thought you wanted the exact result you say in your comment and the end of your question. Commented Nov 7, 2018 at 0:13

1 Answer 1

2

Yes, you are right, according to the npm documentation, you must pass extra " -- " to specify arguments to an npm script, but you do not pass it at the right place.

You do not need to pass it at the end of your package.json "test" script, but directly in the command line which call your script.

This way, npm understand it is arguments for your script and not for the npm command itself:

// cli
$ npm run test -- FOO --BAR 99RedBalloons    // "--" before arguments
  /* or */
$ npm run test -- FOO --BAR=99RedBalloons

// package.json
"scripts": {
   "test": ". ./.env; node app.js"
 }

// app.js
const { argv } = require('yargs');
console.log(argv);

// -> { _: [ 'FOO' ], BAR: '99RedBalloons', '$0': 'app.js' }

I did not find a yargs built-in option to do it, but alternatively, if you want all your arguments in the _ array variable, you can do something like this:

for (let cmd in argv)
  if (cmd !== '$0' && cmd !== '_')
    argv._[cmd] = argv[cmd]

console.log(argv._)

// -> [ 'FOO', BAR: '99RedBalloons' ]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.