【问题标题】:How do I pipe input to a Node.js program that uses readline-sync?如何将输入通过管道传输到使用 readline-sync 的 Node.js 程序?
【发布时间】:2020-09-24 16:56:59
【问题描述】:

我有一个非常简单的 Node.js 程序,它使用readline-sync 接受输入,然后将其回显到控制台:

const readlineSync = require('readline-sync');

const input = readlineSync.prompt();
console.log(input);

它作为一个交互式程序运行良好;但是,当我尝试将输入通过管道传递给它时(在 Git Bash 或 PowerShell 中),我得到一个 Node.js 错误:

PS> echo "1.2" | node .\index.js
Windows PowerShell[35552]: c:\ws\src\node_file.cc:1631: Assertion `(argc) == (5)' failed.

添加#!/usr/bin/env node shebang 并将其作为带有echo "1.2" | .\script.js 的脚本运行会产生相同的错误。

是否有允许readline-sync 从管道读取输入的配置选项或我缺少的东西?我在 shell 中运行它的方式有问题吗?任何建议将不胜感激。

【问题讨论】:

    标签: node.js shell pipe


    【解决方案1】:

    这很可能是您使用的节点版本的包兼容性问题。您需要检查所有依赖项是否与您正在使用的节点版本兼容。

    【讨论】:

      【解决方案2】:
      • 我认为您的程序以“参数”的形式获取“输入”,而不是来自“标准输入”。

      • 当你使用 '|' , 输入将作为“stdin”而不是“argument”提供给程序

      • 所以要转换来自 '|' 的 'stdin'对于“输入参数”,我们可以在 linux 中使用“xargs”。

      在 linux/bash 上尝试以下操作,看看它是否有效:

      echo "1.2" | xargs .\script.js
      
      • 举个例子,我们可以看到'echo'命令的功能,它只能以'arguments'的形式接受'input',而不是'stdin':
      # following command does print anything :
      
      echo boo | echo
      
      # but when xargs is used after | , It displays the output :
      
      echo boo | xargs echo
      boo
      
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-08-09
        • 2023-03-08
        • 1970-01-01
        • 2016-03-17
        • 1970-01-01
        • 2015-08-19
        • 2014-02-03
        • 1970-01-01
        相关资源
        最近更新 更多