node.js - 何时使用服务器发送的事件推送数据

标签 node.js server-sent-events

我想在将新记录添加到数据库时流式传输数据。现在,我每 10 秒为每个连接的用户查询数据库一次新记录。有更好的方法吗?我觉得我应该在插入新记录后引发事件,并以某种方式访问​​相关用户的请求和用户流。

(我简化了我的代码以使要点清晰。所以,它可能无法完全正常工作。)

router.get("/event",  (req, res, next) => {
  let userId = getUserIdFromRequest(req);
  getData(userId, (err, data) => {
    let stream = res.push("/notification/new");
    stream.end(JSON.stringify(data));
    res.write("data:/notification/new\n\n");
    res.flush();
  });
});

getData(userId, callback) {
 model.find( {where: { and: [{ "userId": userId }, { "notified": false }] }}, (err, data =>) {
   callback(null , data);
   setTimeout(function () { getData(callback); }, 10000);
   if (data) {
     setDataAsNotified(data); // makes notified: true
   } 
 })
}

前端:

let source = new EventSource("/route/notification/event")
source.onmessage = (event) => {
 // display notification
}

最佳答案

  • 前端/后端链接:您可以使用WebSockets 。这样数据通过 TCP 而不是 HTTP 传输(速度更快且使用更少的资源)
  • 数据库查询:由于您没有提供在数据库中输入数据的方式,因此这里有两条线索:

    如果您可以修改插入数据的代码,则使其通过 WebSockets(或根据需要通过 HTTP,但 WebSocket 更快)将这些数据发送到后端,并更新数据库记录(或新连接的用户)

    如果你不能,这里有一个链接:How to listen for changes to a MongoDB collection?

希望这有帮助

关于node.js - 何时使用服务器发送的事件推送数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43937472/

相关文章:

python - NodeJs : Get output of python-shell to send back to client

javascript - 无法解析 mongodb json 响应 - javascript

node.js - 通过stream.end()后重新打开写入流

ruby-on-rails - 如何在rails 3中实时推送内容

javascript - `onmessage` 和 `.addEventListener` 有什么区别?

node.js - 尝试了解 Await/Async,这是正确的转换吗?

javascript - 谷歌云功能不处理信号

javascript - 更改 EventSouce 事件名称在 asp.net 中不起作用

javascript - 服务器使用 NodeJS 和 Redis 发送事件

Javascript Promise().then 防止在执行第一次调用之前重新调用该函数