In a Node.js application, you can accept arguments from the command line by following these steps:
-
When invoking your Node.js application from the command line, you can pass any number of arguments. For example:
node app.js
Arguments can be standalone values or have a key-value pair format.
-
To retrieve the command line arguments in your Node.js code, you can use the
process
object provided by Node.js. This object exposes anargv
property, which is an array containing all the command line arguments.- The first element of the
argv
array is the full path of thenode
command. - The second element is the full path of the file being executed.
- All the additional arguments start from the third position in the array.
- The first element of the
-
To iterate over all the command line arguments (including the node path and the file path), you can use a loop:
process.argv.forEach((val, index) => { console.log(`${index}: ${val}`); });
-
If you only need the additional arguments and want to exclude the first two elements, you can create a new array using the
slice()
method:const args = process.argv.slice(2);
-
If you have an argument without an index name, such as
node app.js flavio
, you can access it using theargs
array at index0
:const args = process.argv.slice(2); args[0];
-
If you have an argument with a key-value pair format, such as
node app.js name=flavio
, you can parse it using theminimist
library. Theminimist
library helps handle command line arguments in Node.js applications. To use it, you can install it usingnpm
:npm install minimist
Then, in your code, you can require the
minimist
module and pass theprocess.argv.slice(2)
array as an argument:const args = require('minimist')(process.argv.slice(2)); args['name']; //flavio
By following these steps, you can easily accept and handle command line arguments in your Node.js program.