Node.js, accept arguments from the command line
You can pass any number of arguments when invoking a Node.js application using
BASHnode app.js
Arguments can be standalone or have a key and a value.
For example:
BASHnode app.js joe
or
BASHnode app.js name=joe
This changes how you will retrieve this value in the Node.js code.
The way you retrieve it is using the process
object built into Node.js.
It exposes an argv
property, which is an array that contains all the command line invocation arguments.
The first element is the full path of the node
command.
The second element is the full path of the file being executed.
All the additional arguments are present from the third position going forward.
You can iterate over all the arguments (including the node path and the file path) using a loop:
JSprocess.argv.forEach((val, index) => {console.log(`${index}: ${val}`);});
You can get only the additional arguments by creating a new array that excludes the first 2 params:
JSconst args = process.argv.slice(2);
If you have one argument without an index name, like this:
BASHnode app.js joe
you can access it using
JSconst args = process.argv.slice(2);args[0];
In this case:
BASHnode app.js name=joe
args[0]
is name=joe
, and you need to
parse it. The best way to do so is by using the minimist
library, which helps dealing with arguments:
JSconst args = require('minimist')(process.argv.slice(2));args.name; // joe
Install the required minimist
package using npm
(lesson about the package manager comes later on).
BASHnpm install minimist
This time you need to use double dashes before each argument name:
BASHnode app.js --name=joe