在标准输入关闭之前,NodeJS 不会 运行 来自标准输入管道的代码
NodeJS doesn't run code from pipe on stdin until after stdin is closed
我有一个 python 程序 运行 的 js 代码。但是,节点 js 在标准输入关闭之前不会 运行 它收到的任何代码,即使系统调用跟踪确认它已成功从其标准输入中读取该内容。有关详细信息,请参阅 。在关闭标准输入之前,有什么方法可以执行 运行 命令吗?
这也可以在没有 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")
};
};
然后我将启动程序并写入文件 myinput
并将其用作标准输入。
我有一个 python 程序 运行 的 js 代码。但是,节点 js 在标准输入关闭之前不会 运行 它收到的任何代码,即使系统调用跟踪确认它已成功从其标准输入中读取该内容。有关详细信息,请参阅
这也可以在没有 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")
};
};
然后我将启动程序并写入文件 myinput
并将其用作标准输入。