To send command line arguments to an NPM script, we pass the arguments after --
.
Let's take this simple CLI made with yargs
as an example. The command to run this would be npm start <args>
.
{"name": "node-math","dependencies": {"yargs": "13.2"},"bin":{"node-math" : "index.js"},"scripts": {"start": "node index.js"}}
yargs
package.a
as add with usage help.add
argument is provided, all the values following it will be added up using reduce
and printed to the console.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)); }
An output of 15
will be printed to the console.