Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

passing arguments to a node script coming from stdin

Tags:

shell

node.js

overview

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

more detail

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 time

echo "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
like image 336
user3276552 Avatar asked Aug 24 '15 00:08

user3276552


2 Answers

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
like image 111
Jordan Martin Avatar answered Nov 14 '22 22:11

Jordan Martin


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.

like image 27
browles Avatar answered Nov 14 '22 21:11

browles