【问题标题】:Bash + Node.js + stdin/stdout redirection: error "not a tty"Bash + Node.js + stdin/stdout 重定向:错误“不是 tty”
【发布时间】:2017-12-20 03:22:22
【问题描述】:

此问题可能是特定于 Windows 的。我没有在 Linux 或 Mac 上测试过。

我用:

  • Windows 7 64 位
  • Node.js 8.1.3
  • Git for Windows 2.8.1,包括 GNU bash,版本 4.3.42(5)-release

node my-cli.js > foo.txt:错误output is not a tty

node my-cli.js < foo.txt:错误input is not a tty

【问题讨论】:

    标签: node.js stdout stdin git-bash mingw-w64


    【解决方案1】:

    创建文件my-cli:

    #!/bin/sh
    
    node "path/to/my-cli.js" "$@"
    exit $?
    

    致电./my-cli > foo.txt./my-cli < foo.txt

    这也适用于参数:./my-cli --answer 42 > foo.txt

    【讨论】:

    • 与 git-bash 一起工作到 ./my-cli | grep "something I am looking for" 而这将返回 input is not a tty 而没有这个额外的脚本文件。
    • 你知道为什么会这样吗?
    【解决方案2】:

    发生这种情况是因为默认设置下的 Windows 版 Git 将获取此文件 /etc/profile.d/aliases.sh,它将执行 alias node="winpty node.exe",这是与 node 交互使用所必需的(以及其他程序,如 python,... )。所以当你调用node xxx <yyy >zzz时,你的shell实际上是在后台调用winpty node xxx

    winpty 通过使用新的隐藏控制台窗口启动 winpty-agent.exe 进程来工作,该窗口在控制台 API 和终端输入/输出转义码之间架起了桥梁。它轮询隐藏控制台的屏幕缓冲区以查找更改并生成相应的输出流。

    ,但副作用是stdin和stdout不被识别为tty的。

    因此,当管道或重定向时,您需要调用 node 二进制文件本身而不是别名。有一些方法可以实现这一点:

    1. 包装在一个 shell 脚本中,该脚本将直接调用 node,因为非交互式 shell 不获取 aliases.sh 文件。查看其他答案(shbash 都有效)

    2. 致电
      env node my-cli.js > foo.txt
      command node my-cli.js > foo.txt

    env在默认环境下运行命令,效果与上述方法相同;而command 是一个内置的bash shell,用于绕过别名。

    1. 致电
      \node my-cli.js > foo.txt
      'node' my-cli.js > foo.txt
      "node" my-cli.js > foo.txt

    反斜杠和引号是显式绕过别名的构造。

    1. 拨打电话
      node.exe my-cli.js > foo.txt or
      /full/path/to/node my-cli.js > foo.txt or
      relative/path/to/node my-cli.js > foo.txt

    别名是node,不是node.exe,也不是path/to/node,它仍然指向实际的二进制文件。

    扩展这些解决方案的一种方法是编写一个包装脚本来检测piping/redirection(这本身就是另一个挑战),它将决定是否使用winpty

    【讨论】:

      【解决方案3】:

      sh -c 'node my-cli.js' > foo.txt 为我工作

      【讨论】:

        猜你喜欢
        • 2017-04-02
        • 2015-04-01
        • 1970-01-01
        • 2014-12-24
        • 1970-01-01
        • 1970-01-01
        • 2012-09-25
        • 1970-01-01
        • 2021-04-18
        相关资源
        最近更新 更多