EN
Node.js - get arguments from command line
0
points
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' ]