3

I am trying to pass argument in my npm command and use that argument in my script

Example:

npm run test -b chrome -e QA

"scripts": {
    "test": "something.js ./xyz/abc/cdf --something \"{\\\"browser\\\": \\\"<process.argv[2]>\\\"}\""
}

I am not sure, how to access in my script.

Please advice

1 Answer 1

4

In something.js you can access the process arguments by process.argv.

It will be an array of x elements, where the first two are the executable running your script and the second is a path to the script that is being ran.

Try console.log(process.argv); to see whats up.

In your specific example you should remove the escaped " characters to get it working, like so:

running node in terminal

node somethings.js ./xyz/abc/cdf --something "{\\\"browser\\\": \\\"<process.argv[2]>\\\"}"

Results in:

[ '/usr/local/bin/node', '/Users/user/Documents/test.js', './xyz/abc/cdf', '--something', '{\\"browser\\": \\"<process.argv[2]>\\"}' ]


package.json script

"scripts": { "test": "node test.js" },

Note: add node as the executable in the test script

Running npm run test -b chrome -e QA

Results in:

[ '/usr/local/bin/node', '/Users/user/Documents/test.js', 'chrome', 'QA' ]

If you'd like to get the -b and -e arguments in there too, add --. Like so:

npm run test -- -b chrome -e QA

Results in

[ '/usr/local/bin/node', '/Users/user/Documents/test.js', '-b', 'chrome', '-e', 'QA' ]

Sign up to request clarification or add additional context in comments.

1 Comment

No worries! Glad I could help :)

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.