Close Menu
    Facebook X (Twitter) Instagram
    TecAdmin
    • Home
    • FeedBack
    • Submit Article
    • About Us
    Facebook X (Twitter) Instagram
    TecAdmin
    You are at:Home»General Articles»How To Pass Command-Line Arguments to Node.js Program

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

    By RahulAugust 1, 20191 Min Read

    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

    Related Posts

    How to Change Port in Next.Js

    Ubuntu 24.04 LTS: The Future of Open-Source Excellence

    How to Execute Linux Commands in Python

    Add A Comment

    Leave A Reply Cancel Reply

    Advertisement
    Recent Posts
    • How to Change Port in Next.Js
    • Ubuntu 24.04 LTS: The Future of Open-Source Excellence
    • How to Execute Linux Commands in Python
    • Creating MySQL User with GRANT OPTION
    • Where to find crontab (cron) logs in Ubuntu & Debian
    Facebook X (Twitter) Instagram Pinterest
    © 2023 Tecadmin.net. All Rights Reserved | Terms  | Privacy Policy

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