How to Use process.argv in Node.js to Access Command Line Arguments
In Node.js,
process.argv is an array that contains command line arguments passed when running a script. The first two elements are the Node.js executable path and the script file path, and the following elements are the actual arguments you provide. You can access these arguments by indexing process.argv or by slicing it to get only the user inputs.Syntax
process.argv is an array where:
- process.argv[0] is the path to the Node.js executable.
- process.argv[1] is the path to the JavaScript file being executed.
- process.argv[2] and onward are the command line arguments passed by the user.
You usually use process.argv.slice(2) to get only the user arguments.
javascript
console.log(process.argv); console.log(process.argv.slice(2));
Example
This example shows how to print the command line arguments passed to a Node.js script.
Run the script with arguments like node script.js hello world.
javascript
const args = process.argv.slice(2); console.log('User arguments:', args); // Example usage: // node script.js hello world // Output: User arguments: [ 'hello', 'world' ]
Output
User arguments: [ 'hello', 'world' ]
Common Pitfalls
Many beginners try to access process.argv[0] or process.argv[1] expecting user input, but these are reserved for Node.js and script paths.
Always slice the array starting from index 2 to get actual arguments.
Also, command line arguments are strings, so convert them if you expect numbers.
javascript
/* Wrong way: */ console.log('First argument:', process.argv[0]); // Prints node path, not user input /* Right way: */ const userArgs = process.argv.slice(2); console.log('User arguments:', userArgs);
Quick Reference
| Index | Description |
|---|---|
| 0 | Path to Node.js executable |
| 1 | Path to the executed script file |
| 2 and above | User-provided command line arguments |
Key Takeaways
Use process.argv to access command line arguments in Node.js scripts.
Skip the first two elements to get only user inputs with process.argv.slice(2).
All arguments are strings; convert them if needed for numbers or other types.
Avoid accessing process.argv[0] or [1] for user data as they hold system paths.