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)
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With