从stdin传递参数到Node脚本

8

概述

我希望能够从标准输入(stdin)中向一个node脚本传递参数。

通常情况下,我希望做到以下这点:

nodeScript.js | node {{--attach-args??}} --verbose --dry-run

该操作将与之前的操作相同

node nodeScript.js --verbose --dry-run

更多细节

这里有一个简化的脚本用于举例dumpargs.js

console.log("the arguments you passed in were");
console.log(process.argv);
console.log("");

那么你可以:

node dumpargs.js --verbose --dry-run file.txt
[ 'node',
  '/home/bill-murray/Documents/dumpargs.js',
  '--verbose',
  '--dry-run',
  'file.js' ]

现在的问题是,如果该脚本通过标准输入流(例如通过 catcurl)输入

cat dumpars.js | node
the arguments you passed in were
[ 'node' ]

有没有一种好的方法将参数传递给它?

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
2个回答

7

这个用例有特定的语法。文档中写道:

- 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.

那么请按照以下步骤操作:
$ cat script.js | node - args1 args2 ...

例如,这将返回“hello world”:
$ echo "console.log(process.argv[2], process.argv[3])" | node - hello world

3

这不太美观,但很有效。

调用node将启动REPL,因此您的问题应该相当于手动从终端设置/使用argv。尝试执行类似以下内容的操作:

// argv.js
process.argv[1] = 'asdf';
process.argv[2] = '1234';

并且执行 cat argv.js dumpargs.js | node 命令。


1
据我所知,没有办法像bash-s选项一样使用预设的argv启动node REPL。 - browles

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接