How can we send command line arguments to an NPM script?
Overview
To send command line arguments to an NPM script, we pass the arguments after -- .
Example
Let's take this simple CLI made with yargs as an example. The command to run this would be npm start <args>.
index.js
package.json
{"name": "node-math","dependencies": {"yargs": "13.2"},"bin":{"node-math" : "index.js"},"scripts": {"start": "node index.js"}}
Explanation
- Line 1: We import the
yargspackage.
- Lines 3–9: We define the option
aas add with usage help.
- Line 11–13: We define a condition, which states that if the
addargument is provided, all the values following it will be added up usingreduceand printed to the console.
Running the script
This CLI takes -a <number> <number2>... as an argument.
Here is an example command to pass arguments to the script:
npm start -- -a 1 4 5 5
Here, npm start is the script that is used to run our program, and the arg a is provided after double dashes ( -- ). All the numbers will be added and the result will be printed to the console.
Click the "Run" button in the widget below and enter this command.
const yargs = require("yargs");
const options = yargs
.usage("Usage: $0 -a <number1> <number2> <number3> ...")
.option("a", {
alias: "add",
describe: "Add multiple numbers",
type: "number",
}).argv;
if (yargs.argv.add) {
const numbers = yargs.argv._;
console.log(options.add + numbers.reduce((a, b) => a + b));
}Output
An output of 15 will be printed to the console.