Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

How to print command line arguments passed to the script in Node.js ?

  • Last Updated : 10 Oct, 2021

Node.js is an open-source and cross-platform runtime environment built on Chrome’s V8 engine that enables us to use JavaScript outside the browser. Node.js helps us to use build server-side applications using JavaScript. 

In Node.js if you want to print the command line arguments then we can access the argv property on the process object. process.argv returns an array that contains the absolute path of Node.js js executable as the first argument, the absolute file path of the running script, and the command line arguments as the rest of the element. We can pass the command line arguments to our script using the following command on the command line.

Syntax:

node file-name.js argument1 argument2 argumentN

Steps to print command-line arguments:

Step 1: Install Node.js if Node.js is not installed on your machine.



Step 2: Create an app.js file in the particular directory.

Project Structure: After following the steps your project structure will look like the following.

app.js




const args = process.argv;
  
console.log(args);
args.forEach((e, idx) => {
  // The process.argv array contains
  // Node.js executable absolute
  // path as first element
  if (idx === 0) {
    console.log(`Exec path: ${e}`);
  }
  
  // Absolute file path is the second element
  // of process.argv array
  else if (idx === 1) {
    console.log(`File Path: ${e}`);
  }
  
  // Rest of the elements are the command
  // line arguments the we pass
  else {
    console.log(`Argument ${idx - 1}: ${e}`);
  }
});


Run app.js file using below command:

node app.js geeks for geeks

Output:

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!