Node.js is full of utilities and tools that can make the development of our projects easier. One such tool is NPM. NPM has been around for 10 years and comes pre-installed with Node.js. NPM is more popularly known for being the default package manager for Node.js but its functionality doesn’t end here. Apart from being a command-line tool that allows you to install, update and manage JavaScript packages, NPM offers a feature known as “npm scripts”, which are a series of commands that can be executed using the command “npm run”.
If you want to learn more about npm from the beginning, check out this article on Beginner’s Guide to NPM
npm scripts are useful for running customized commands. npm scripts can also accept arguments via the terminal and perform operations accordingly. In this article, we will write a simple npm script and learn how we can customize our script by sending command-line arguments to it.
Setup an npm script
Before writing the npm script, we need to create a project folder and initialize a Node project. Run the following command in your terminal to do so.
mkdir demo-npm-script
cd demo-npm-script
Our project folder is created. Now we can initialize a Node project inside our folder using the command
npm init --y
We can see a package.json file has been created inside our project folder. It contains all the metadata related to our project. We can also see the scripts section. This is where we can add the custom commands that we wish to run using npm run.
{
"name": "demo-npm-script",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC"
}
Now create an index.js file inside the project folder and paste the following code
index.js
const firstName = "John"
const lastName = "Doe"
console.log("Hello", firstName, lastName)
This is just plain JavaScript that takes the values from two variables firstName and lastName and then logs them to the console with a Hello. We can simply run this code by the command node index.js but to run it via npm we need to make some changes to our package.json.
Inside the scripts section in package.json add a new key “greetings” with the value “node index.js”.
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"greetings": "node index.js"
}
We can invoke this greetings command in our terminal by simply calling:
npm run greetings
So, our npm script is ready, now we can understand how to send command-line arguments and use them in the npm script.
Sending command line arguments to the npm script
Arguments for npm scripts are similar to parameters that we pass in a function. So far our npm script logs Hello John Doe which is hard coded in our application. What if we wanted to make our script dynamic by logging the argument we pass in the terminal?
We can send firstName as an argument in this way:
npm run greetings --firstName="Jane"
Similarly, we can also send the second argument lastName into our npm script:
npm run greetings --firstName="Jane" --lastName="Doe"
Once we have passed the arguments to our script, the question arises, “How can we access them in the script?”
We can retrieve the provided argument by accessing the environment variables through the process.env object. npm has a built-in argument parser that attaches the arguments to the process.env object with a prefix of npm_config_.
index.js
const firstName = process.env.npm_config_firstName? process.env.npm_config_firstName:"John"
const lastName = process.env.npm_config_lastName? process.env.npm_config_lastName:"Doe"
console.log("Hello", firstName, lastName)
We have made modifications in our index.js file above to access the value of firstName and lastName directly from the argument and in case the argument is missing a default value is used.
Now we can test the script by passing different arguments:
npm run greetings --firstName="Rohit" --lastName="Agarwal"
Output:
Hello Rohit Agarwal
Additionally, we can also access our arguments from the process.argv when we pass arguments without using “–” before the argument name. process.argv produces an array of arguments so unlike the former method we need to write a parser function.
index.js
// Argument parser
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)); // { firstName: 'Rohit', lastName: 'Agarwal' }
const firstName = args.firstName? args.firstName:"John"
const lastName = args.lastName? args.lastName:"Doe"
console.log("Hello", firstName, lastName)
Again, test the script by passing different arguments:
npm run greetings firstName="Rohit" lastName="Agarwal"
Output:
Hello Rohit Agarwal
For process.argv every space-separated string in the terminal is an argument so, in the above example, parseArgs function takes the array of arguments provided by process.argv and parses it by splitting the argument string where it finds “=” to create a JavaScript object with the passed argument name as key and argument value as object value. We can then use the args object to log firstName and lastName in the terminal.
Conclusion
Sending command-line arguments is a great way to make your scripts more dynamic and customizable. In this article, we covered how we can create a simple npm script, send command-line arguments and access them from process.env and process.argv.
Wondering what to read next? Learn about the use of tilde and caret symbol in package.json.
Reference
https://stackoverflow.com/questions/11580961/sending-command-line-arguments-to-npm-script