Trusted answers to developer questions

How can we send command line arguments to an NPM script?

Get the Learn to Code Starter Pack

Break into tech with the logic & computer science skills you’d learn in a bootcamp or university — at a fraction of the cost. Educative's hand-on curriculum is perfect for new learners hoping to launch a career.

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 yargs package.
  • Lines 3–9: We define the option a as add with usage help.
  • Line 11–13: We define a condition, which states that if the add argument is provided, all the values following it will be added up using reduce and 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.

RELATED TAGS

nodejs
npm
Did you find this helpful?