如何将输入通过管道传输到使用 readline-sync 的 Node.js 程序?

How do I pipe input to a Node.js program that uses readline-sync?

我有一个非常简单的 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 中 运行 有什么问题吗?如有任何建议,我们将不胜感激。

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

  • 我认为您的程序正在以 'argument' 的形式获取 'input' 而不是来自 'stdin'.

  • 当您使用“|”时, 输入将作为 'stdin' 而不是 'argument'

    提供给程序
  • 所以要转换来自'|'的'stdin' 'input argument' 我们可以在 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