Skip to content

How To Pass Command-Line Arguments to Node.js Program

Node.js stores all the command line arguments in an array. How To Pass Command-Line Arguments to Node.js Program. Using process.argv in node.js

Covers
Node.js
Versions & support
About Node.js →

Node.js stores all the command line arguments in an array. The first element of an array is the node command (binary location) itself. The second element is the javascript file we refer to that often comes after the node command. After that, the arguments are stored in third, fourth and so on.

To understand this create a sample Node.js script and execute script with some arguments. For example, assuming the following script for process-args.js:

Launching the Node.js process as:

node process-args.js hello "Rahul Kumar" 123

Would generate the output:

0: /usr/local/bin/node
1: /home/rahul/process-args.js
2: hello
3: Rahul Kumar
4: 123

To access the single argument, simply use process.argv[INDEX] option. Change index number as per your need.

OR

Rahul

Rahul Kumar is the founder and chief editor of TecAdmin.net. A Red Hat Certified Engineer (RHCE), he has worked in IT since 2009, with hands-on experience in Linux system administration, DevOps, web hosting, cloud platforms and automation. He started TecAdmin in 2013 to share practical, step-by-step guides, and leads its editorial work with one aim: making technical learning clear and useful for sysadmins, developers and beginners alike.

Leave a Reply

Your email address will not be published. Required fields are marked *


Back to top