Node.js 将参数传递给来自stdin的节点脚本 概述
我想将参数传递给来自stdin的节点脚本 一般来说,我是在为这样的事情而努力Node.js 将参数传递给来自stdin的节点脚本 概述,node.js,shell,Node.js,Shell,我想将参数传递给来自stdin的节点脚本 一般来说,我是在为这样的事情而努力 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)
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' ]
现在的问题是,如果该脚本遇到stdin(比如,通过cat
或curl
)
有没有一个好方法可以传递参数给它
非节点:使用bash,这次使用dumpargs.sh
echo "the arguments you passed in were"
printf "> $@"
echo
答案看起来是这样的
cat dumpargs.sh | bash -s - "--verbose --dry-run file.txt"
the arguments you passed in were
> --verbose --dry-run file.txt
这并不漂亮,但很管用 调用
节点
将启动REPL,因此您的问题应等同于从终端手动设置/使用argv
。试着做一些类似的事情:
// argv.js
process.argv[1] = 'asdf';
process.argv[2] = '1234';
执行
cat argv.js dumpargs.js | node
时,该用例有一个特定的语法。医生说:
- 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”:
否则,无法使用预设的
argv
启动节点
REPL,就像bash的-s
选项一样。
$ cat script.js | node - args1 args2 ...
$ echo "console.log(process.argv[2], process.argv[3])" | node - hello world