node.js - 查询一个表,然后使用 knex 和 postgres 将结果流式传输到 socket.io

标签 node.js postgresql sockets socket.io knex.js

我想查询一个表并将内容写入套接字,以进行更大的查询。 I was reading the documentation for streams .我试图用 socket.io 来实现这个。下面是我的 /users 路由示例,其中 appexpress 的一个实例,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/

相关文章:

c++ - boost async_write() 和 non_blocking socket.send() 之间的区别

node.js - Mongoose 查询中是否有相当于 Promise.all 的东西?

database - 从 subselect 语句结果数组更新 select 语句

node.js - 如何创建 Node JS 服务器

sql - 查找 PostgreSQL 中两个大表之间的差异

node.js - 数据库 "public"不存在 - postgres/sequelize

java - TCP 连接 - 服务器仅在关闭套接字后发送消息

python - 在python3中使用现有的父类(super class)实例初始化子类

javascript - Node.js : SocketIO vs http request performance

node.js - 在Nodejs中使用q(promises)模块时,then()返回的值是多少?