# index.js
console.log(process.argv) // expect this to print [.., .., '1']
# terminal
$ echo 1 | node index.js // just prints [.., ..]
What's the trick? How do I dynamically pass arguments to a node script from the command line via unix commands like echo
, ls
, ps aux
, and so on?
Note: I see that I can read the output of unix commands from within my script using stdin
, but what I'd like is to truly pass arguments to the script from the command line.
$ echo 1 | node index.js
In this command echo
prints 1
to the standard output which is redirected (via pipe) to the standard input of the node
command that accepts index.js
argument. If you want to read the string printed by echo
, read the standard input, e.g.:
var text = '';
process.stdin.setEncoding('utf8');
process.stdin.on('readable', function () {
var chunk = process.stdin.read();
if (chunk !== null) {
text += chunk;
}
});
process.stdin.on('end', function () {
console.log(text);
});
How do I dynamically pass arguments to a node script from the command line via unix commands like echo, ls, ps aux, and so on.?
With a pipe you can only redirect the bulk output from a command. You may use command substitution to pass the outputs of multiple commands as strings, e.g.:
node index.js --arg1="$(ls -ld /tmp)" --arg2="$(stat -c%a /tmp)"
Assign the output of the commands to shell variables in order to make your script more readable:
arg1="$(ls -ld /tmp)"
node index.js --arg1="$arg1"
A friend of mine showed me this:
$ node index.js `echo 1 2 3 4`
Actually does exactly what I want. This would result in:
// index.js
process.argv // [.., .., '1', '2', '3', '4']
The difference between this and @RuslanOsmanov answer is that the above will pass in the output as all the arguments to the node process, whereas:
$ node --arg1=`echo 1` --arg2=`echo 2`
Requires an individual command for each individual argument.
It would not work as expected with ls
if your filenames contain spaces, as space characters are treated as argument delimiters.
See What does the backtick - ` - do in a command line invocation specifically with regards to Git commands? for more about this use of back ticks.
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