Introduction
When developing Node.js applications, npm
scripts are often used for automation tasks like starting servers or running tests. Sometimes, it is necessary to pass dynamic arguments to these scripts. This tutorial explores various methods to achieve this using npm version 2 and later.
Understanding npm Scripts
An npm script is defined in the scripts
section of your package.json
. For example:
{
"scripts": {
"start": "node ./script.js server"
}
}
Running npm start
executes the command specified, in this case, starting a Node.js application. However, there are times when you need to pass additional parameters directly from the command line.
Passing Arguments with npm
Method 1: Using Argument Separator (–)
From npm version 2 onwards (released in 2014), you can use an argument separator --
to pass arguments to your scripts:
npm run <command> [-- <args>]
The syntax separates the parameters meant for npm itself from those intended for your script.
Example:
Suppose you want to start a server on port 8080 using a script in package.json
:
{
"scripts": {
"start": "node server.js"
}
}
You can pass the argument as follows:
npm run start -- --port=8080
This command tells npm to execute node server.js --port=8080
.
Note: If your parameter does not start with -
or --
, explicitly using --
is clearer, though optional.
Method 2: Environment Variables
Another approach involves using environment variables. This method allows you to set a variable in the command line, which can be accessed within your script:
{
"scripts": {
"start": "node ./script.js server $PORT"
}
}
Run with an environment variable:
PORT=8080 npm start
Here, $PORT
is used to pass the port number dynamically.
Method 3: Using npm Config
You can also use npm_config_
variables for more complex configurations. For instance:
In your package.json
:
{
"scripts": {
"start": "node ./script.js server ${npm_config_port}"
}
}
Run with:
npm start --port=8080
Within your script, you can access the port using process.env.npm_config_port
.
Note: Be aware of case sensitivity; environment variable keys are lowercase by default.
Method 4: Script-Specific Variables
If you prefer to set variables within the npm command itself:
{
"scripts": {
"start": "NODE_ENV=production node server.js"
}
}
Run using:
npm run start
Here, NODE_ENV
is directly set in your script.
Best Practices
- Consistency: Choose a method that aligns with the rest of your project’s configuration and team practices.
- Security: Avoid passing sensitive data through command-line arguments without proper sanitization.
- Documentation: Document how to use scripts, especially when dynamic parameters are involved, for ease of collaboration.
Conclusion
Passing arguments to npm scripts is a powerful feature that enhances flexibility in development workflows. By leveraging different methods such as argument separators, environment variables, and npm configurations, you can tailor your scripts to meet specific project requirements efficiently.