forked from zacbarton/node-server-sent-events
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
33 lines (26 loc) · 766 Bytes
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
function sse(req, res, next) {
req.socket.setKeepAlive(true);
req.socket.setTimeout(0);
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
res.setHeader('Connection', 'keep-alive');
res.status(200);
// export a function to send server-side-events
res.sse = function sse(string) {
res.write(string);
// support running within the compression middleware
if (res.flush && string.match(/\n\n$/)) {
res.flush();
}
};
// keep the connection open by sending a comment
var keepAlive = setInterval(function() {
res.sse(':keep-alive\n\n');
}, 20000);
// cleanup on close
res.on('close', function() {
clearInterval(keepAlive);
});
next();
}
module.exports = sse;