我想查询一个表并将内容写入套接字,以进行更大的查询。 I was reading the documentation for streams .我试图用 socket.io 来实现这个。下面是我的 /users
路由示例,其中 app
是 express
的一个实例,io
是一个 socket.io
实例。
module.exports = function (app, io) {
app.get('/users', function (req, res, next) {
const limit = req.queryParams.limit || 100;
const stream = req.db.select('*').from('users').limit(limit).stream();
req.on('close', stream.close.bind(stream)); // manually close on request cancel
// how can you stream to the socket?
// how do you know when the amount is reached to end the response?
});
}
我想知道的是; 如何将此查询的结果流式传输到 io 套接字?我想在每次找到结果时发出一个 added
事件,使用表名、id 和找到的条目作为参数。
最佳答案
how can you stream to the socket?
您可以通过监听来自 knex 流的 data
事件并通过 io.emit
将数据传递到 socket.io 来访问流式 DB 行。
how do you know when the amount is reached to end the response?
流将发出一个 end
事件。
当 end
事件触发时,您知道流已完成,但由于您在 HTTP channel 上接受请求,但通过单独的 Web 套接字 channel 进行响应,因此您可以将 HTTP 响应发送到 res
如果您愿意,无需等待数据库查询结果 (res.send()
)。
module.exports = function (app, io) {
app.get('/users', function (req, res, next) {
const limit = req.queryParams.limit || 100;
const stream = req.db.select('*').from('users').limit(limit).stream();
stream.on('data', function (row) {
io.emit('user', row)
})
.on('error', function (error) {
io.emit('error', error.message)
})
.on('end', function () {
io.emit('end')
})
req.on('close', stream.close.bind(stream)); // manually close on request cancel
// how can you stream to the socket?
// how do you know when the amount is reached to end the response?
});
}
关于node.js - 查询一个表,然后使用 knex 和 postgres 将结果流式传输到 socket.io,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35133089/