I'd like to pass arguments to a node script coming from stdin.
generally, I'm shooting for something like this
nodeScript.js | node {{--attach-args??}} --verbose --dry-run
that would act the same as
node nodeScript.js --verbose --dry-run
here's a boiled down script for illustration, dumpargs.js
console.log("the arguments you passed in were");
console.log(process.argv);
console.log("");
so you could then:
node dumpargs.js --verbose --dry-run file.txt
[ 'node',
'/home/bill-murray/Documents/dumpargs.js',
'--verbose',
'--dry-run',
'file.js' ]
now the question, if that script comes in across stdin (say, via cat
or curl
)
cat dumpars.js | node
the arguments you passed in were
[ 'node' ]
is there a good way to pass arguments to it?
not node: with bash, using
dumpargs.sh
this timeecho "the arguments you passed in were" printf "> $@" echo
the answer would look like
cat dumpargs.sh | bash -s - "--verbose --dry-run file.txt" the arguments you passed in were > --verbose --dry-run file.txt
There is a specific syntax for this use case. The doc says :
- Alias for stdin, analogous to the use of - in other command line utilities, meaning
that the script will be read from stdin, and the rest of the options are passed to
that script.
-- Indicate the end of node options. Pass the rest of the arguments to the script.
If no script filename or eval/print script is supplied prior to this, then the next
argument will be used as a script filename.
So just do the following :
$ cat script.js | node - args1 args2 ...
For example, this will returns "hello world" :
$ echo "console.log(process.argv[2], process.argv[3])" | node - hello world
This isn't pretty, but works.
The call to node
is going to launch the REPL, so your problem should be equivalent to setting / using argv
manually from the terminal. Try doing something like:
// argv.js
process.argv[1] = 'asdf';
process.argv[2] = '1234';
and doing cat argv.js dumpargs.js | node
.
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