在 node.js 中,我发送到 stdin 的数据只有在我调用 end() 后才能到达进程。如果我想继续写作怎么办?



如果我这样做:

child = child_process.spawn('./resources/backend-exe', {stdio: ['pipe', 'pipe', 'ignore']});
child.stdin.write("Testn");

子进程没有反应,就好像没有向它发送任何内容一样。但是,如果我这样做(添加一行(:

child = child_process.spawn('./resources/backend-exe', {stdio: ['pipe', 'pipe', 'ignore']});
child.stdin.write("Testn");
child.stdin.end();

它像往常一样对数据做出反应,并向标准输出发送响应。但是,这意味着我无法再写入流。如果我想写几次怎么办?如何在不关闭流的情况下"刷新"数据?

以下是子进程(Haskell(的完整代码:

module Main where
main :: IO ()
main = do
line <- getLine
putStrLn line
main

当您调用.write()时,数据将在一段时间后自动刷新。
(如果想知道刷新何时发生,可以提供回调.write()或监听drain事件(

例如:

child.stdin.write("Testn", () => console.log("FLUSHED!"));

下面是两个进程之间乒乓球的工作示例: repl.it 控制台

如果要处理子进程的输出,请将pipe传递给 stdio 并侦听 stdout 上的data

const child_process = require('child_process');
child = child_process.spawn('./program', {stdio: ['pipe', 'pipe', 'ignore']});
// listen for messages from our child
child.stdout.on('data', chunk => {
console.log("Child sent line: " + chunk.toString());
});
// send a message to the child
child.stdin.write("Testn");

(有关完整示例,请参阅 repl.it 控制台(

编辑: 您的问题似乎与缓冲有关。 Haskell将检查您的程序是否在tty上下文中运行,即程序直接连接到控制台,并相应地设置缓冲策略。

如果你从控制台启动你的Haskell程序,Haskell将使用LineBuffering。
但是,如果您在非 tty 上下文中调用它,它将使用块缓冲。 您可以通过调用来重置缓冲策略

hSetBuffering stdin LineBuffering
hSetBuffering stdout LineBuffering

使用LineBufferingNoBuffering让Haskell进程再次响应每一行。

相关内容

最新更新