【问题标题】:passing arguments to a node script coming from stdin将参数传递给来自标准输入的节点脚本
【发布时间】:2015-08-24 00:51:14
【问题描述】:

概述

我想将参数传递给来自标准输入的节点脚本。

一般来说,我正在拍摄这样的东西

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' ]

有没有好办法给它传递参数?

不是节点:使用 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

【问题讨论】:

    标签: node.js shell


    【解决方案1】:

    这不漂亮,但有效。

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

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

    然后做cat argv.js dumpargs.js | node

    【讨论】:

    • AFAIK 无法启动带有预设 argvnode REPL,例如 bash-s 选项。
    【解决方案2】:

    此用例有特定的语法。医生说:

    - 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
    

    【讨论】:

      猜你喜欢
      • 2020-11-15
      • 2017-12-13
      • 2016-04-09
      • 2018-05-05
      • 2021-11-13
      • 1970-01-01
      • 1970-01-01
      • 2015-02-25
      • 2022-01-23
      相关资源
      最近更新 更多