Year-End Discount: 10% OFF 1-year and 20% OFF 2-year subscriptions!

Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

nodejs
npm

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

Dhravya Shah

Tired of LeetCode? 😩

Learn the 24 patterns to solve any coding interview question without getting lost in a maze of LeetCode-style practice problems. Practice your skills in a hands-on, setup-free coding environment. πŸ’ͺ

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

Tired of LeetCode? 😩

Learn the 24 patterns to solve any coding interview question without getting lost in a maze of LeetCode-style practice problems. Practice your skills in a hands-on, setup-free coding environment. πŸ’ͺ

Keep Exploring
Related Courses