-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy patheventsource.js
67 lines (56 loc) · 1.71 KB
/
eventsource.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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
'use strict';
module.exports = function(req, res) {
var counter = 0,
maxMessages = 10,
seconds = 3,
interval = null;
//prepare response header
var prepareResponseHeader = function(response) {
//prepare header
response.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive',
'Access-Control-Allow-Origin': '*'
});
//the following 2 lines were added for IE support: 2kb padding, and a retry param
response.write(':' + (new Array(2049)).join(' ') + '\n');
response.write('retry: 2000\n');
//clear interval when the client stops listening
response.on('close', function() {
clearInterval(interval);
console.log('Client stopped listening');
});
};
//data object to be returned - currently a random number, but can be anything
var preparePayload = function(messageId) {
return {
id: messageId,
data: Math.floor(Math.random() * 1000000).toString(),
time: (new Date()).toLocaleTimeString(),
final: false
};
};
//send message back to client
var sendMessage = function() {
var data = preparePayload(++counter);
//after max messages sent, send final message and zero the counter
if (counter > maxMessages) {
clearInterval(interval);
data.final = true;
data.data = 'the end';
counter = 0;
}
//convert message to string
data = JSON.stringify(data);
console.log(data);
//send message back
res.write('id: ' + counter + '\n');
res.write('event: data\n');
res.write('data: ' + data + '\n\n');
};
//prepare response header
prepareResponseHeader(res);
//send a message containing current time and data (random number) every n seconds
interval = setInterval(sendMessage, seconds * 1000);
};