如何使用expresss .js流生成器?



这是我现在使用的:

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();
})

客户端是否有可能使用生成器获得下一个酒吧对象,客户端控制何时将下一个酒吧对象流式传输?

谢谢robertklep的建议。我用的是插座。IO实现一个简单的例子。客户端控制流的速度

服务器端

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);
});

客户端

<!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>

相关内容

  • 没有找到相关文章

最新更新