AmouxTechnerd AmouxTechnerd - 2 months ago 5x
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 = 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

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

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


To get all args you can use


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:


To skip two elements you can use something like:

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

or process.argv.slice(2)