我的目标是:将标准输入从echo输送到节点文件和,通过提示符请求更多输入。但是我需要知道哪个输入来自管道,哪个输入来自提示。
节点文件x.js如下所示:
const readline = require("readline");
let rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question("yes or no? (y/n)", answer => {
console.log("-" + answer + "-");
rl.close();
});这个操作(显示了一个提示符,我输入了"hello“并将其写到控制台):
> node x.js -hello-
但这不起作用(没有提示)。)将管道字符串写入控制台:):
> echo "abcdefgh" | node x.js -abcdefgh-
如何区分这两种标准输入?
发布于 2019-12-16 15:33:03
实际上,你的问题比你想象的还要糟糕--问题不在于区分管道输入和键盘输入,而是首先能够接受两者。
当您传输数据时,您基本上是在说“--这是我的输入”--应用程序不能再捕获键盘输入,而且实际上stdin在读取管道数据之后立即关闭。
你完全骨瘦如柴吗?这取决于你想做什么。根据您的示例,如果您想让用户在接受它之前确认某件事情是正常的,您可以使用命令行参数:
var stdin = process.stdin;
if (stdin.setRawMode)
{
// No data is being piped, so fall back to your existing code
const readline = require("readline");
let rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question("yes or no? (y/n)", answer =>
{
console.log("-" + answer + "-");
rl.close();
});
}
else
{
// resume stdin in the parent process (node app won't quit all by itself
stdin.resume();
// on any data into stdin
let receivedData = '';
stdin.on('data', (data) => {
receivedData += data;
});
stdin.on('end', () => {
// Input will have a \n appended
receivedData = receivedData.slice(0, -1);
console.log('I received "' + receivedData + '".');
const args = process.argv.slice(2);
for(const arg of args)
{
if (arg.toLowerCase() === '--accept')
{
console.log('Accepted the input!');
return;
}
}
console.log('Is this OK? If so, pass --accept as a parameter');
});
}它的作用是这样的:
~ # echo "abcdefhiy" | node input.js
I received "abcdefhiy".
Is this OK? If so, pass --accept as a parameter
~ # echo "abcdefhiy" | node input.js --accept
I received "abcdefhiy".
Accepted the input!发布于 2020-04-30 18:32:57
https://stackoverflow.com/questions/59308117
复制相似问题