Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getting raw command line arguments in node.js

How can I get the raw command line arguments in a node.js app, given this example command:

node forwardwithssh.js echo "hello arguments"

process.argv will be [ "node", "/path/to/forwardwith.js", "echo", "hello arguments" ]

And there's no way to reconstruct the original echo "hello arguments" from that (ie. join(" " won't put quotes back). I want the whole original raw string after the script name.

what I want is easily obtained in bash scripts with "$*", is there any equivalent way to get that in node.js?

Note: the intention in particular is to receive a command to be executed somewhere else (eg. thru ssh)

like image 478
Benja Avatar asked Jul 21 '14 20:07

Benja


People also ask

How do I get command line arguments?

If you want to pass command line arguments then you will have to define the main() function with two arguments. The first argument defines the number of command line arguments and the second argument is the list of command line arguments.

Which object holds all arguments in node JS?

The arguments object is a special construct available inside all function calls. It represents the list of arguments that were passed in when invoking the function.

Which object holds all arguments passed after executing a script with node command?

The argument vector is an array available from process. argv in your Node. js script. The array contains everything that's passed to the script, including the Node.


1 Answers

Wrap each of the args in single quotes, and escape and single quotes within each arg to '\'':

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

That would give you a cmd_string containing:

'node' '/path/to/forwardwith.js' 'echo' 'hello arguments'

which can be run directly in another shell.

like image 53
Paul Avatar answered Oct 21 '22 14:10

Paul