我想将参数传递给来自 stdin 的节点脚本。
一般来说,我正在拍摄这样的东西
nodeScript.js | node {{--attach-args??}} --verbose --dry-run
Run Code Online (Sandbox Code Playgroud)
这将与
node nodeScript.js --verbose --dry-run
Run Code Online (Sandbox Code Playgroud)
这是一个简化的说明脚本,dumpargs.js
console.log("the arguments you passed in were");
console.log(process.argv);
console.log("");
Run Code Online (Sandbox Code Playgroud)
这样你就可以:
node dumpargs.js --verbose --dry-run file.txt
[ 'node',
'/home/bill-murray/Documents/dumpargs.js',
'--verbose',
'--dry-run',
'file.js' ]
Run Code Online (Sandbox Code Playgroud)
现在的问题是,如果该脚本出现在标准输入中(例如,通过cat或curl)
cat dumpars.js | node
the arguments you passed in were
[ 'node' ]
Run Code Online (Sandbox Code Playgroud)
有没有一种好方法可以将参数传递给它?
不是节点:使用 bash,
dumpargs.sh这次使用Run Code Online (Sandbox Code Playgroud)echo "the arguments you passed in were" printf "> $@" echo答案看起来像
Run Code Online (Sandbox Code Playgroud)cat dumpargs.sh | bash -s - "--verbose --dry-run file.txt" the arguments you passed in were > --verbose --dry-run file.txt
小智 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.
Run Code Online (Sandbox Code Playgroud)
所以只需执行以下操作:
$ cat script.js | node - args1 args2 ...
Run Code Online (Sandbox Code Playgroud)
例如,这将返回“hello world”:
$ echo "console.log(process.argv[2], process.argv[3])" | node - hello world
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2184 次 |
| 最近记录: |