Command Line Arguments in JavaScript

Command-line arguments are a common way to parameterize execution of programs. For example, node script.js uses script.js as an argument to the node program.

// In Node.js, we can access command-line arguments 
// through the process.argv array

// The first element is the path to the Node.js executable
// The second element is the path to the JavaScript file being executed
// The remaining elements are any additional command-line arguments

function main() {
    // Get all arguments, including the Node.js executable and script name
    const argsWithProg = process.argv;

    // Get only the additional arguments (excluding Node.js executable and script name)
    const argsWithoutProg = process.argv.slice(2);

    // You can get individual args with normal indexing
    const arg = process.argv[4]; // Note: This is equivalent to the 3rd additional argument

    console.log(argsWithProg);
    console.log(argsWithoutProg);
    console.log(arg);
}

main();

To experiment with command-line arguments, you can save this code in a file (e.g., command-line-arguments.js) and run it with Node.js:

$ node command-line-arguments.js a b c d
[ '/path/to/node', '/path/to/command-line-arguments.js', 'a', 'b', 'c', 'd' ]
[ 'a', 'b', 'c', 'd' ]
c

In JavaScript (Node.js), we use process.argv to access command-line arguments. The first two elements of process.argv are always the path to the Node.js executable and the path to the JavaScript file being executed, respectively. The remaining elements are the additional command-line arguments.

Next, we’ll look at more advanced command-line processing with option parsing libraries in JavaScript.