Languages
[Edit]
EN

Node.js - get arguments from command line

0 points
Created by:
Aran-Busby
532

In this article, we would like to show you how to get arguments from command line in Node.js.

Quick solution:

const arguments = process.argv;

// skip the first two
const arguments2 = process.argv.slice(2);

 

1. Practical example using process.argv

In this example, we use process.argv to get the arguments from command line. The arguments should be specified in the running command.

const arguments = process.argv;

console.log(arguments);

1.1 Run the app without arguments:

node index.js

Output:

[
  'C:\\Program Files\\nodejs\\node.exe',
  'C:\\projects\\app\\index.js'
]

1.2 Run the app with arguments:

node index.js arg1 arg2 arg3 

Output:

[
  'C:\\Program Files\\nodejs\\node.exe',
  'C:\\projects\\app\\index.js',        
  'arg1',
  'arg2',
  'arg3'
]

2. Skip the first two arguments

In this example, we present how to skip the first two arguments of the process.argv when you don't need them.

const arguments = process.argv.slice(2);

console.log(arguments);

2.1 Run the app without arguments:

node index.js

Output:

[]

2.2 Run the app with arguments:

node index.js arg1 arg2 arg3 

Output:

[ 'arg1', 'arg2', 'arg3' ]

References

Alternative titles

  1. Node.js - parse command line arguments
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join