/

Accepting Command Line Arguments in Node.js

Accepting Command Line Arguments in Node.js

In a Node.js application, you can accept arguments from the command line by following these steps:

  1. When invoking your Node.js application from the command line, you can pass any number of arguments. For example:

    1
    node app.js

    Arguments can be standalone values or have a key-value pair format.

  2. To retrieve the command line arguments in your Node.js code, you can use the process object provided by Node.js. This object exposes an argv property, which is an array containing all the command line arguments.

    • The first element of the argv array is the full path of the node 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.
  3. To iterate over all the command line arguments (including the node path and the file path), you can use a loop:

    1
    2
    3
    process.argv.forEach((val, index) => {
    console.log(`${index}: ${val}`);
    });
  4. 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:

    1
    const args = process.argv.slice(2);
  5. If you have an argument without an index name, such as node app.js flavio, you can access it using the args array at index 0:

    1
    2
    const args = process.argv.slice(2);
    args[0];
  6. If you have an argument with a key-value pair format, such as node app.js name=flavio, you can parse it using the minimist library. The minimist library helps handle command line arguments in Node.js applications. To use it, you can install it using npm:

    1
    npm install minimist

    Then, in your code, you can require the minimist module and pass the process.argv.slice(2) array as an argument:

    1
    2
    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.

tags: [“node.js”, “command line arguments”, “process.argv”, “minimist”]