Solved: How to PROPERLY pass arguments to npm script


NodeJS

Author: Steve Alila
Reviewer: Deepak Prasad

Knowing how to pass arguments to npm script lets you control your Node.js development environment.

npm run <command> [-- <arguments>]

You need to build the command in the package.json file and create the arguments in your Node.js script, attaching them to npm argument parser object.

This tutorial teaches you how to pass arguments to npm script by explaining the key concepts while highlighting the relationship between npm and the (Node) environment. Lastly, the tutorial walks you through relatable examples to ease absorbing the concepts.

Let's do this!

 

Key concepts to understand before knowing how to pass arguments to npm script

The first step toward understanding how to pass arguments to npm script is grasping the knowledge of arguments, package managers and Node scripts.

Arguments

An argument is a value you pass to a function when calling it. For example, we can declare an area-calculating function with the length and width placeholder variables.

const area = (length, width) => length * width;
const sixByEight = area(6, 8); // 48
const twoByNine = area(2, 9); // 18

We then return the output of length by width. The output depends on the arguments passed into the function when calling it. For example, the function outputs 48 when we pass to it 6 and 8. The same function outputs 18 when called with 2 and 9.

Similarly, an npm argument changes the behavior and output of your Node.js script. However, this time around, we pass the arguments with unique options to the text-based CLI environment.

It would be best to understand the fundamental CLI operations before looking at some relatable examples of how to pass arguments to npm scripts.

 

Package managers

A package manager installs, controls, and uninstalls packages. A package is a collection of the files of the target tool.

Most packages depend on others for operation. The other packages are called dependencies.

We mainly use package managers in Unix-based operating systems. For example, Linux's most familiar package manager is the advanced package tool, often abbreviated as apt.

apt looks inside the /etc/apt/sources.list or /etc/apt/sources.list.d directories for the URLs to repositories of the target packages and their dependencies. It then downloads the needed files, storing their binaries in the /usr directory in either /bin, /local or /share subdirectories.

We can manage or uninstall the package using the same tool.

Likewise, npm checks for files and dependencies in npm repositories or GitHub. It downloads the packages, storing their information as follows.

  • implementation details => node_modules,
  • versions => package-lock.json,
  • project metadata => package.json.

The package.json file lets us write commands which we can later run on the terminal with the npm run command. Such commands are called npm scripts.

The most typical scripts are start, test, and build. Besides, we can create custom scripts. For instance, we can create a script called calculateArea with the values: node index.js. We then run the script.

npm run calculateArea

The best part of custom scripts is seen when automating or passing arguments to an npm script. But how does that happen? Here is the answer.

 

An in-depth explanation of how to pass arguments to npm script

The simplest way to pass arguments to an npm script is to prepend the arguments to the argument parser called npm_config_ and attach the result to the process.env object.

The process object is the interface between the operating system environment and your Node environment. It enables writing and reading to the operating system through its multiple objects like the env property. As a result, we can access the operating system's environment variables or attach custom environment variables to it.

The built-in npm_config_ argument parser enables our arguments to be visible to the node script.

process.env.npm_config_[argument]
# e.g
process.env.npm_config_length

We then run the script, attaching double dashes to the argument and then assigning the argument a value.

npm run [command] --argument=[value]
# e.g
npm run calculateArea --length=6

We can also create and pass multiple arguments.

process.env.npm_config_length
process.env.npm_config_width
npm run calculateArea --length=6 --width=8

Additionally, we can read the arguments in the script file as variables by appending the dollar sign to the argument name.

"calculateArea": "node index.js $LENGTH"

Now that you understand the origin of npm arguments, let's set up a lab and see how to pass arguments to npm script.

 

Lab setup to practice how to pass arguments to npm script

The primary prerequisite to handling scripts is having a package.json file. Let's create the file by initializing npm.

First, create and open a working directory using a target code editor. I am using Visual Studio Code with Ubuntu in this tutorial.

Open your terminal and run each of these commands till you have a package.json

$ mkdir working_directory
$ cd working_directory
$ npm init -y
$ touch index.js
$ code .

The -y flag creates a default package.json.

Solved: How to PROPERLY pass arguments to npm script

Next, customize the package.json file to use ECMAScript modules and a (custom) dev script.

{
"name": "working_directory",
"version": "1.0.0",
"description": "",
"main": "index.js",
"type":"module",
"scripts": {
"dev": "node index.js"
},
"keywords": [],
"author": "",
"license": "ISC"
}

Now let's see how to pass arguments to npm script practically.

 

How to pass arguments to npm script practically

Example~1: Pass single argument

Assume we want to find the area of a square by specifying the length as an npm argument. Open the Node script file and calculate the area with the length placeholder.

const length = process.env.npm_config_length;
const area = length * length;
console.log("The area is => ", area);

Open the terminal and run the script file with --length argument with a value of 4.

npm run dev --length=4

We get the expected 16 area output.

The area is => 16

How to pass arguments to npm script

Likewise, we could create a server that listens on a port we pass as an argument to the npm script.

index.js:

import { createServer } from 'http';

const server = createServer((request, response) => {
if (request.url === '/')
response.end('How to pass arguments to npm script.');
})

const PORT = process.env.npm_config_port || 3000;
server.listen(PORT, console.log('Listening on port', PORT));

terminal:

npm run dev --port=2022

Output:

Listening on port 2022

Solved: How to PROPERLY pass arguments to npm script

Bonus tricks

We can also specify the PORT in the package.json file and remove the argument parser.

Modify the script with the PORT variable preceded with the dollar sign.

"dev": "node index.js $PORT"

Next, let the process.env object read the PORT argument without prepending the variable with theĀ  npm_config_ argument parser.

const PORT = process.env.PORT || 3000

Lastly, run the script, inputting the PORT value before npm script.

PORT=2022 npm run dev

We get an output similar to the previous one.

Listening on port 2022

Solved: How to PROPERLY pass arguments to npm script

 

Example~2: Pass multiple arguments

Assume we want to calculate an area of a rectangle using length and width arguments. We can introduce the width variable.

const length = process.env.npm_config_length;
const width = process.env.npm_config_width;
const area = length * width;
console.log("The area is => ", area);

And pass its arguments like the length's.

Input:

npm run dev --length=6 --width=8

Output:

The area is => 48

Solved: How to PROPERLY pass arguments to npm script

 

Conclusion

In this tutorial, you learned how to pass arguments to npm script using process.env and npm_config_ in objects. Before that, the tutorial covered an overview of npm and why you may need to pass arguments to an npm script.

 

Further Reading

Sending command line arguments to npm script

 

Related Keywords: pass variable to npm script, npm script arguments 1, npm script argument , laceholder, npm run all pass arguments, npm run script, npm script default argument, npm script positional arguments, npm arguments

Steve Alila

Steve Alila

He specializes in web design, WordPress development, and data analysis, with proficiency in Python, JavaScript, and data extraction tools. Additionally, he excels in web API development, AI integration, and data presentation using Matplotlib and Plotly. You can connect with him on his LinkedIn profile.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to admin@golinuxcloud.com

Thank You for your support!!

Leave a Comment