Front-end Development
How-tos & Guides
7 min read

Sending command-line arguments to an npm script

Node is a popular open-source JavaScript runtime environment for efficiently executing JavaScript code on the server. Node can also be configured to run your own JavaScript code as scripts on the command line.

Vijit Ail
Published July 13, 2022
AI Assistant for Playwright
Code AI-powered test steps with the free ZeroStep JavaScript library
Learn more

Node.js is full of utilities and CLI tools that let you customize them to do exactly what you want. If you need something really custom, though, “npm scripts” are the way to go. You might have used this for your “build” or “dev” scripts, but there’s a lot more you can do with them. npm scripts are the commands you can execute in a Node.js project using npm run.

When you’re developing an npm script, you’ll need some input to be able to tell the script what needs to be done with these values. This is where command-line arguments will come in handy! In this guide, you will learn how to create a simple npm script and pass input values to the script using command-line arguments.

What is npm?

If you’re a Node.js developer, it’s very likely that you have some experience with npm. It’s Node’s favorite sidekick, and it’s been around for more than 10 years now!.

npm is a package manager for JavaScript, and it’s become increasingly popular as the go-to tool for managing dependencies in modern web development. But what exactly is npm, and why do you need it?

In a nutshell, npm is a command-line tool that lets you install, update, and manage packages of code used in JavaScript applications. If you’re working on a project that uses a lot of different libraries and frameworks, npm can help you keep them all organized and up to date. It’s also a great way to share your own code with other developers – if you’ve written a library that you think others might find useful, you can publish it to npm and make it available for anyone to install.

So why do you need it? Well, if you’re doing any kind of serious JavaScript development, chances are you’re going to be using a lot of third-party libraries. Managing all of these dependencies manually would be a huge pain – but with npm, it’s easy. Just install the libraries you need with a few simple commands, and npm will keep track of them for you. When updates are available, it will let you know.

One of the most common tasks for an npm script is to take a set of command-line arguments and use them in some way. This can be as simple as parsing out values inside the arguments, or parsing numbers from a date string, or even more complex, like constructing a SQL query. A lot of developers like to use the command line to control their scripts, clean up builds, and automate tedious tasks.

To follow along with this guide, you will need to install npm on your local machine. You can check out npm’s docs for installation instructions.

Writing a Simple Command Line Script

Now, let’s get into some practical stuff and start writing a simple script that will display a random number.

First you need to create a node project. Open up your terminal and create a project folder.

1
2
mkdir npm-script-demo
cd npm-script-demo

Next, initialize the node project by running the following command.

1
npm init --y

This command will create a package.json file in your project folder.

A package.json file contains essential metadata about a Node project, and is often used by developers to publish their project on the npm repository and install it into other projects. In this file we find things such as the title, a description, version, and dependencies of the project.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
{
  "name": "npm-script-demo",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

Inside your project, create an index.js file. The index.js file will be the main script that we will be running from the command line.

Let’s write a simple javascript program that will print a random number less than 10.

1
2
3
const max = 10;
const num = Math.floor(Math.random() * max);
console.log("Random Number : ", num);

You can run this code using the following command.

1
node index.js

Now to make it run via npm you need to add the command in the scripts object in your package.json file.

1
2
3
4
"scripts": {
  "test": "echo \"Error: no test specified\" && exit 1",
  "generateNumber": "node index.js"
},

The scripts in the package.json file are commands that run throughout the development and publishing process. The start command is one of the most common npm scripts, which is usually specified to start the node process.

npm scripts can be executed using the following syntax -

1
npm run <scriptName>

So to run the generateNumber script, you need to run the following in your terminal.

1
npm run generateNumber

How to pass arguments to the npm script

So far we have discussed how to create npm scripts and run them using the npm run command.

In the earlier section we created a script that will generate a random number less than 10. Here the value 10 is hardcoded. We can make the script dynamic using command line arguments as shown below.

1
npm run generateNumber --maxNumber=50

npm has a built-in argument parser which enables developers to access the passed argument values in their scripts. The passed argument can be accessed through the environment variables using process.env object and the arguments will be prefixed with npm_config_.

You can checkout the below code to see the variable in action.

1
2
3
4
5
const max = process.env.npm_config_maxNumber || 10;

const num = Math.floor(Math.random() * max);

console.log("Random Number : ", num);

You can also pass multiple arguments to the script. For example, we can modify our JavaScript code to print a random number between a min and max value.

1
npm run generateNumber --maxNumber=50 --minNumber=30
1
2
3
4
5
6
7
const max = process.env.npm_config_maxNumber ? parseInt(process.env.npm_config_maxNumber) : 10;

const min = process.env.npm_config_minNumber ? parseInt(process.env.npm_config_minNumber) : 0;

const num = Math.floor(Math.random() * (max - min + 1)) + min;

console.log("Random Number : ", num);

Alternatively, you can also use the following method to pass arguments.

1
npm run generateNumber -- maxNumber=50 minNumber=30

Here the arguments will be passed directly to the node program which can be accessed using process.argv object.

Let’s add a console log and see what’s the value of process.argv when we run the above command.

1
console.log(process.argv);

You will see a similar output as follow.

1
2
3
4
5
6
[
  "/usr/local/Cellar/node@12/12.22.1_1/bin/node",
  "/Users/mac/Desktop/Projects/NodeJS/npm-script-demo/index.js",
  "maxNumber=50",
  "minNumber=30"
]

The process.argv contains an array that includes all the arguments that you passed in the command line.

Note that the first two elements here are the node and the path to your scripts. These values will always be present irrespective of any other arguments passed or not.

To omit the first two values from process.argv you can use the slice array method.

1
2
const args = process.argv.slice(2);
console.log(args); // [ 'maxNumber=50', 'minNumber=30' ]

As you can see, unlike in the previous method, here you need to parse the values from the arguments. To do that you can write a small helper function that will return a key-value object with the argument name and value.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
const parseArgs = (args) => {
  const parsedArgs = {};

  args.forEach((arg) => {
    const parts = arg.split("=");

    parsedArgs[parts[0]] = parts[1];
  });

  return parsedArgs;
};

const args = parseArgs(process.argv.slice(2));

console.log(args); // { maxNumber: '50', minNumber: '30' }

Now, the rest of the code can be modified as shown below.

1
2
3
4
5
6
7
const max = args.maxNumber ? parseInt(args.maxNumber) : 10;

const min = args.minNumber ? parseInt(args.minNumber) : 0;

const num = Math.floor(Math.random() * (max - min + 1)) + min;

console.log("Random Number : ", num);

Conclusion

Sending command-line arguments to an npm script can be a great way to customize the behavior of your scripts. With a little bit of knowledge, you can use arguments to make your scripts more flexible and powerful. I hope this article has helped you understand how to use arguments in your own scripts. Thanks for reading!

Get started with Reflect today

Create your first test in 2 minutes, no installation or setup required. Accelerate your testing efforts with fast and maintainable test suites without writing a line of code.

Copyright © Reflect Software Inc. All Rights Reserved.