gpt4 book ai didi

node.js - nodejs/express - 立即将标准输出流式传输到客户端

转载 作者:IT老高 更新时间:2023-10-28 22:59:30 27 4
gpt4 key购买 nike

我产生了以下 child :var spw = spawn('ping', ['-n','10', '127.0.0.1']) 我想接收 ping结果在客户端(浏览器)一个一个,而不是作为一个整体。

到目前为止,我尝试过这个:

app.get('/path', function(req, res) {
...
spw.stdout.on('data', function (data) {
var str = data.toString();
res.write(str + "\n");
});
...
}

还有:

...
spw.stdout.pipe(res);
...

在这两种情况下,浏览器都会等待 10 个 ping 完成,然后将结果作为一个整体打印出来。我想一一拥有,如何实现?

(客户端只是调用 .../path 并且 console.logs 结果)


编辑:虽然我确实相信 websockets 是实现这一点所必需的,但我只想知道是否还有其他方法。我看到几个令人困惑的SO answers ,和博客文章(在 this 帖子中,在第一步 OP 将日志流式传输到浏览器)没有帮助,因此我决定寻求赏金以引起注意。

最佳答案

这是一个使用 SSE(服务器发送事件)的完整示例。这适用于 Firefox,也可能适用于 Chrome:

var cp = require("child_process"),
express = require("express"),
app = express();

app.configure(function(){
app.use(express.static(__dirname));
});


app.get('/msg', function(req, res){
res.writeHead(200, { "Content-Type": "text/event-stream",
"Cache-control": "no-cache" });

var spw = cp.spawn('ping', ['-c', '100', '127.0.0.1']),
str = "";

spw.stdout.on('data', function (data) {
str += data.toString();

// just so we can see the server is doing something
console.log("data");

// Flush out line by line.
var lines = str.split("\n");
for(var i in lines) {
if(i == lines.length - 1) {
str = lines[i];
} else{
// Note: The double-newline is *required*
res.write('data: ' + lines[i] + "\n\n");
}
}
});

spw.on('close', function (code) {
res.end(str);
});

spw.stderr.on('data', function (data) {
res.end('stderr: ' + data);
});
});

app.listen(4000);

和客户端 HTML:

<!DOCTYPE Html>
<html>
<body>
<ul id="eventlist"> </ul>

<script>
var eventList = document.getElementById("eventlist");
var evtSource = new EventSource("http://localhost:4000/msg");

var newElement = document.createElement("li");
newElement.innerHTML = "Messages:";
eventList.appendChild(newElement);


evtSource.onmessage = function(e) {
console.log("received event");
console.log(e);
var newElement = document.createElement("li");

newElement.innerHTML = "message: " + e.data;
eventList.appendChild(newElement);
};

evtSource.onerror = function(e) {
console.log("EventSource failed.");
};

console.log(evtSource);

</script>

</body>
</html>

运行 node index.js 并将浏览器指向 http://localhost:4000/client.html。请注意,我必须使用“-c”选项而不是“-n”,因为我运行的是 OS X。

关于node.js - nodejs/express - 立即将标准输出流式传输到客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21934831/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com