NodeJS 不会从 stdin 上的管道运行代码,直到 stdin 关闭之后



我有一个运行js代码的python程序。然而,节点js直到stdin关闭后才运行它接收到的任何代码,即使系统调用跟踪确认它成功地从stdin中读取了该内容。有关更多信息,请参阅此处(已接受的答案(。在stdin关闭之前,有什么方法可以运行命令吗?

这也可以在没有Python的情况下复制,使用bash如下:

{
echo 'console.log("HI");'
sleep 1
echo 'console.log("HI");'
sleep 1
echo "Sent both commands to node with one second delay after each" >&2
} | node

其输出为:

Sent both commands to node with one second delay after each
HI
HI

而如果Node在收到代码后立即执行代码,则会看到:

HI
HI
Sent both commands to node with one second delay after each

我对这个问题的解决方案是制作我自己的微型交互式控制台:

const fs = require('fs');
while (true){
const data = fs.readFileSync("myinput", "utf8");
if (data){
try{
console.log(data);
eval(data)
} catch(err) {
console.log(err)
};
fs.writeFileSync("myinput", "", "utf8")
};
};

然后,我将启动该程序并将其作为stdin写入文件myinput

最新更新