[英]How to use generators with exprerss.js streams?
This is what i am using at the moment:这就是我目前正在使用的:
app.get('/foo', (req, res) => {
res.set('Content-type', 'text/plain');
res.set('Transfer-Encoding', 'chunked');
const stream = new Stream.Readable({ read() { } });
stream.pipe(res);
for (let i = 0; i < 10; i++) {
let result = JSON.stringify({ bar: i});
res.cork();
stream.push(`${result}\n`);
freeze(50);
process.nextTick(() => res.uncork());
}
res.end();
})
Is it possible that the client gets the next bar object using a generator, sort of the client controls when then next bar object will be streamed?客户端是否有可能使用生成器获取下一个 bar 对象,客户端控制什么时候下一个 bar 对象将被流式传输?
Thanks robertklep for the suggestion.感谢robertklep的建议。 I used socket.io to implement a simple example.我使用 socket.io 来实现一个简单的例子。 The client controls the pace of the stream.客户端控制流的速度。
Server side服务器端
const express = require('express');
const app = express();
const http = require('http');
const { Server } = require("socket.io");
function* numsGenerator() {
for (let i = 0; i < 10; i++) {
yield i;
}
}
const server = http.createServer(app);
const io = new Server(server, { cors: { origin: '*' } });
io.of("/stream").on("connection", (socket) => {
const gen = numsGenerator();
socket.on('stream:get', () => {
socket.emit('stream:result', gen.next());
});
});
const port = 4000;
server.listen(port, () => {
console.log('\nReady for requests on http://localhost:' + port);
});
Client side客户端
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script type="module">
import { io } from "https://cdn.socket.io/4.5.1/socket.io.esm.min.js";
const socket = io("ws://localhost:4000/stream");
socket.emit('stream:get');
socket.on("stream:result", (result) => {
console.log(result);
if (result.done) return;
socket.emit('stream:get');
});
</script>
</body>
</html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.