Facebook Twitter Instagram
    TecAdmin
    • Home
    • Ubuntu 20.04
      • Upgrade Ubuntu
      • Install Java
      • Install Node.js
      • Install Docker
      • Install LAMP Stack
    • Tutorials
      • AWS
      • Shell Scripting
      • Docker
      • Git
      • MongoDB
    • FeedBack
    • Submit Article
    • About Us
    Facebook Twitter Instagram
    TecAdmin
    Home»General Articles»How To Pass Command-Line Arguments to Node.js Program

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

    RahulBy RahulJuly 18, 20191 Min ReadUpdated:August 1, 2019

    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:

    1
    2
    3
    4
    // print process.argv
    process.argv.forEach((val, index) => {
      console.log(`${index}: {val}`);
    });

    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.

    1
    console.log(process.argv[0]);

    OR

    1
    console.log(process.argv[2]);

    node node.js NodeJs
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email WhatsApp
    Previous ArticleHow to Install Docker on Debian 10 (Buster)
    Next Article How to Install Angular CLI on Debian 10/9/8

    Related Posts

    What is CPU? – Definition, Types and Parts

    3 Mins Read

    How to Install Ionic Framework on Ubuntu 22.04

    3 Mins Read

    What is the /etc/hosts file in Linux

    Updated:June 27, 20222 Mins Read

    Creating DMARC Record for Your Domain

    Updated:June 29, 20223 Mins Read

    What is Computer Hardware?

    4 Mins Read

    What is Information Technology (IT)?

    Updated:June 29, 20223 Mins Read

    Leave A Reply Cancel Reply

    Recent Posts
    • What is CPU? – Definition, Types and Parts
    • What is the /etc/aliases file
    • What is the /etc/nsswitch.conf file in Linux
    • How to Install Ionic Framework on Ubuntu 22.04
    • What is the /etc/hosts file in Linux
    Facebook Twitter Instagram Pinterest
    © 2022 Tecadmin.net. All Rights Reserved | Terms  | Privacy Policy

    Type above and press Enter to search. Press Esc to cancel.