AmouxTechnerd AmouxTechnerd - 4 months ago 14
Node.js Question

Concatting arguments after argv[2] NodeJs

Edit: Mykola Borysyuk suggested i use node-optimist, unfortunately the author said its deprecated and to use Minimist.

After reading over it, i get the basic gist of it, but could someone show me an example?




As the title suggests I'm trying to combine multiple arguments for a command.

In other words...
Command goes
node init.js search <value>
.

Obviously I have no idea how many words the user will type after search, so i want to concat all of those 'arguments' into one string i can send to my search module.

I'm aware that I can use the following to "group" all arguments into independent strings

var cmd_string = process.argv.map( function(arg){
return "'" + arg.replace(/'/g, "'\\''") + "'";
}).join(' ');


and this can output all arguments

process.argv.forEach((val, index) => {
console.log(`${index}: ${val}`);
});


But i don't know how i'd go about extracting just the values after
process.argv[2];


Bonus: If possible, could you also show me or link a way i'd be able to search for flags like
--option=value


I spent a couple hours surfing Reddit and Google and came up short, so hopefully you can provide some insight.

Answer

To get all args you can use

process.argv

for example:

node test.js arg1 arg2

process.argv will be like:

[NodeJs path, file path, arg1, arg2]

After you can do all you want with arguments, for example, join in string:

process.argv.join('');

To skip two elements you can use something like:

process.argv.splice(2, process.argv.length - 1)

or process.argv.slice(2)