Course contentsShow
← JavaScript
Lesson 1497 of 2,72333. JavaScript in Node.jsFree lesson

Process.argv: Command-Line Arguments

Accessing command-line arguments passed to your Node.js script through the argv array.

Process.argv: Command-Line Arguments

You'll learn how to read command-line arguments passed to your Node.js script using process.argv.

What Are Command-Line Arguments?

When you run a Node.js script from the terminal, you can pass extra information to it right in the command itself. For example: node app.js hello world 42. Those extra values (hello, world, 42) are called command-line arguments, and they let users customize how your script runs without changing the code.

The process.argv Array

The process object (which you learned about previously) provides access to these arguments through its argv property. This property is an array containing all the arguments passed when Node.js was invoked.

Important structure: process.argv always includes:

  • Index 0: The path to the Node.js executable
  • Index 1: The path to your script file
  • Index 2 onward: Your actual command-line arguments

Reading Arguments

// app.js
console.log(process.argv);

Running node app.js Alice 30 prints something like:

[
  '/usr/local/bin/node',     // argv[0]
  '/Users/you/app.js',        // argv[1]
  'Alice',                    // argv[2] - first real argument
  '30'                        // argv[3] - second real argument
]

To access just your arguments, typically slice from index 2:

const userArgs = process.argv.slice(2);
console.log(userArgs); // ['Alice', '30']

Analogy: Think of process.argv like a guest list at a party—the first two names are always the organizers (Node and your script), and everyone after that is who you actually invited.

Key Takeaway: Use process.argv to access command-line arguments; remember the first two elements are Node's path and your script's path, so your arguments start at index 2.