首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将参数传递给来自stdin的节点脚本

将参数传递给来自stdin的节点脚本
EN

Stack Overflow用户
提问于 2015-08-24 00:51:14
回答 2查看 3.2K关注 0票数 7

概述

我想将参数传递给来自stdin的节点脚本。

一般情况下,我是为了这样的事情而开枪

代码语言:javascript
复制
nodeScript.js | node {{--attach-args??}} --verbose --dry-run

它的作用和

代码语言:javascript
复制
node nodeScript.js --verbose --dry-run

更详细

下面是一个简化的说明脚本,dumpargs.js

代码语言:javascript
复制
console.log("the arguments you passed in were");
console.log(process.argv);
console.log("");

这样你就可以:

代码语言:javascript
复制
node dumpargs.js --verbose --dry-run file.txt
[ 'node',
  '/home/bill-murray/Documents/dumpargs.js',
  '--verbose',
  '--dry-run',
  'file.js' ]

现在的问题是,这个脚本是否贯穿stdin (例如,通过catcurl)

代码语言:javascript
复制
cat dumpars.js | node
the arguments you passed in were
[ 'node' ]

有什么好办法把论点传递给它吗?

非节点:使用bash,这次使用dumpargs.sh 传入的参数为“printf "> $@”echo“ 答案看起来就像 cat dumpargs.sh \ bash -s -“

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-12-24 13:29:55

这个用例有一个特定的语法。医生说:

代码语言:javascript
复制
- 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.

因此,只需做以下几点:

代码语言:javascript
复制
$ cat script.js | node - args1 args2 ...

例如,这将返回"hello world“:

代码语言:javascript
复制
$ echo "console.log(process.argv[2], process.argv[3])" | node - hello world
票数 6
EN

Stack Overflow用户

发布于 2015-08-24 01:39:46

这不是很漂亮,但很管用。

node的调用将启动REPL,因此您的问题应该等同于从终端手动设置/使用argv。试着做这样的事情:

代码语言:javascript
复制
// argv.js
process.argv[1] = 'asdf';
process.argv[2] = '1234';

cat argv.js dumpargs.js | node

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32173065

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档