-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.js
46 lines (38 loc) · 1.13 KB
/
server.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
const fs = require('fs');
const express = require('express');
const getSizes = require('./sizes');
const open = require('opn');
function start({dir, port = 9000}) {
const connections = new Set();
const app = express();
app.get('/', (req, res) => {
const html = __dirname + '/client.html';
fs.createReadStream(html).pipe(res);
});
app.get('/_sse', async (req, res) => {
connections.add(res);
req.connection.addListener('close', () => connections.delete(res));
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
Connection: 'keep-alive',
});
const data = await getSizes(dir);
res.write(`data: ${JSON.stringify(data)}\n\n`);
});
const server = app.listen(port, () => {
console.log(`Running on http://localhost:${port}`);
});
open(`http://localhost:${port}`);
async function update() {
const data = await getSizes(dir);
for (const res of connections) {
res.write('data: ' + JSON.stringify(data) + '\n\n');
}
}
function close() {
server.close();
}
return {update, close};
}
module.exports = {start, getSizes};