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:
xxxxxxxxxx
1
const arguments = process.argv;
2
3
// skip the first two
4
const arguments2 = process.argv.slice(2);
In this example, we use process.argv
to get the arguments from command line. The arguments should be specified in the running command.
xxxxxxxxxx
1
const arguments = process.argv;
2
3
console.log(arguments);
1.1 Run the app without arguments:
xxxxxxxxxx
1
node index.js
Output:
xxxxxxxxxx
1
[
2
'C:\\Program Files\\nodejs\\node.exe',
3
'C:\\projects\\app\\index.js'
4
]
1.2 Run the app with arguments:
xxxxxxxxxx
1
node index.js arg1 arg2 arg3
Output:
xxxxxxxxxx
1
[
2
'C:\\Program Files\\nodejs\\node.exe',
3
'C:\\projects\\app\\index.js',
4
'arg1',
5
'arg2',
6
'arg3'
7
]
In this example, we present how to skip the first two arguments of the process.argv
when you don't need them.
xxxxxxxxxx
1
const arguments = process.argv.slice(2);
2
3
console.log(arguments);
2.1 Run the app without arguments:
xxxxxxxxxx
1
node index.js
Output:
xxxxxxxxxx
1
[]
2.2 Run the app with arguments:
xxxxxxxxxx
1
node index.js arg1 arg2 arg3
Output:
xxxxxxxxxx
1
[ 'arg1', 'arg2', 'arg3' ]