Reading Command Line Arguments with node process.argv
process.argv is an array that can be accessed in your Node.js script. Because it is an array you can a specific element in the array or loop the array and build your variables in the loop:
process.argv.forEach(function (value, index, array) {
console.log(index + '=' + value);
});
Then you can run your application as follows: node index.js arg1 arg2 arg3.
This will output:
0=node
1=/fullpath/to/index.js
2=arg1
3=arg2
4=arg3
It's really important to note that the first two elements in the array are the command node js process argv and the full path to the script being executed. Your arguments don't start until the 3rd element in the array.
This works well for very simple parameters, but it's nice to provide named elements with specific values. For this you can write something custom to parse them out or use an existing library. I'm a big fan of not reinventing the wheel, so let's look at a lightweight library that does it all for us.
Reading Command Line Arguments with minimist
Because this is an npm package you of course need to install the package in your Node.js project: npm install minimist. Now we can use this in our script as follows:
var parameterInput = require('minimist')(process.argv.slice(2));
console.dir(parameterInput);
The library still uses the node process argv array to read the arguments, but notice the use of .slice(2). This removes the first two arguments mentioned above of the command node and the full path to the script being executed.
In our previous example we ran the application as follows: node index.js arg1 arg2 arg3. Using the minimist library it would convert the names to a JSON variable with named elements, e.g.:
{
arg1: true,
arg2: true,
arg3: true
}
Because I didn't provide a value for this named arguments, the library interprets them as a boolean. With this library we can do much more powerful arguments:
node index.js -env local -port 8080 -https
Which would create a JSON object as follows:
{
env: 'local',
port: '8080',
https: true
}
This would allow us, as an example, to start an Express web server using a variable from the input instead of hard-coding in the script:
app.listen(parameterInput.port, function() {
console.log('Running on port: ' + parameterInput.port);
});
Much nicer in my opinion!
Published on Jan 21, 2020
Tags: Node js Tutorial
| slice
| minimist