My answer is not about on how process.argv
works -'cause there is a lot of answers here-, instead, it is on how you can get the values using array destructuring syntax
.
For example, if you run your script with:
node app.js arthur 35
you can get those values in a more readable way like this:
const [node, script, name, age] = process.argv;
console.log(node); // node
console.log(script); // app.js
console.log(name); // arthur
console.log(age); // 35
You can omit the first and second places of your process.argv
, and stay only with name
and age
:
const [, , name, age] = process.argv;
If you want all the arguments in an array, you can do it using the rest syntax
, that collects multiple elements and condenses them into a single element like this:
const [node, script, ...params] = process.argv;
console.log(node); // node
console.log(script); // app.js
console.log(params); // [ 'arthur', '35' ]
and of course, you can omit the first and second places of your process.argv
, and stay only with your params:
const [, , ...params] = process.argv;