Accessing Command-Line Arguments with process.argv
You'll learn how to retrieve and work with the arguments passed to your Node.js script from the command line.
What is process.argv?
When you run a Node.js script from the terminal, you can pass extra information along with it—like node app.js hello world. The process.argv property gives you access to these arguments as an array.
Think of process.argv like a mailbox that automatically collects everything typed on the command line when your script starts. Every word (separated by spaces) becomes an item in the array.
The First Two Elements Are Special
Here's the catch: process.argv doesn't start with your arguments. The first two elements are always:
process.argv[0]— The full path to the Node.js executable (where Node is installed)process.argv[1]— The full path to the JavaScript file being executed
Everything from index 2 onwards contains the actual arguments you passed.
// If you run: node script.js apple banana
console.log(process.argv[0]); // '/usr/local/bin/node'
console.log(process.argv[1]); // '/path/to/script.js'
console.log(process.argv[2]); // 'apple'
console.log(process.argv[3]); // 'banana'
Why the First Two?
Node automatically includes these so your script knows where it's running from and what is running. This can be useful for error messages or resolving relative file paths—but for most tasks, you'll skip straight to process.argv[2] and beyond.
Key Takeaway: process.argv is an array holding command-line arguments, with the Node path at index 0, the script path at index 1, and your custom arguments starting at index 2.