How To Pass And Access Command-Line Arguments In Node.js

Node.js, being a versatile runtime environment, allows developers to create powerful command-line applications effortlessly. Command-line arguments play a crucial role in enabling interaction and customization of these applications. In this guide, we’ll explore how to pass and access command-line arguments in Node.js scripts.

1. Passing Command-Line Arguments

Passing command-line arguments to a Node.js script is straightforward. Arguments are provided as space-separated values when executing the script from the terminal or command prompt.

node script.js arg1 arg2 arg3 ...
node myScript.js hello world 123

2. Accessing Command-Line Arguments

In Node.js, command-line arguments are accessible through the process.argv array. This array contains the command-line arguments provided when executing the script.

  • process.argv[0]: Path to the Node.js executable.
  • process.argv[1]: Path to the JavaScript file being executed.
  • process.argv[2] onwards: User-provided arguments.

Here’s how you can access command-line arguments in your script:

// myScript.js
console.log('Command-line arguments:', process.argv);

// Accessing individual arguments
console.log('First argument:', process.argv[2]);
console.log('Second argument:', process.argv[3]);

Let’s say we have a Node.js script named myScript.js containing the code snippet above. Executing it with the command:

node myScript.js hello world 123

Would produce the following output:

Command-line arguments: [
  '/path/to/node',
  '/path/to/myScript.js',
  'hello',
  'world',
  '123'
]
First argument: hello
Second argument: world

3. Best Practices and Considerations

  • Argument Parsing Libraries: For complex applications, consider using libraries like yargs, commander, or minimist to handle command-line arguments more efficiently.
  • Error Handling: Validate and handle command-line arguments gracefully to prevent unexpected behavior.
  • Documentation: Clearly document the usage of command-line arguments in your scripts for ease of understanding by other developers.