-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
54 lines (43 loc) · 1.08 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
47
48
49
50
51
52
53
const path = require('path')
const express = require('express')
const expressWs = require('express-ws')
const websocketStream = require('websocket-stream')
const RAM = require('random-access-memory')
const hyperdrive = require('hyperdrive')
const pump = require('pump')
const PORT = process.env.PORT || 4000
const app = express()
expressWs(app)
app.use(express.static(__dirname + '/build'))
app.get('/', (req, res) => {
res.sendFile(path.resolve(__dirname + '/build/index.html'))
})
const archives = {}
app.ws('/archive/:key', (ws, req) => {
const { key } = req.params
let archive
if (archives[key]) {
archive = archives[key]
} else {
archive = hyperdrive(RAM, key)
archives[key] = archive
}
archive.ready(() => {
const stream = websocketStream(ws)
const replicationStream = archive.replicate({
live: true
})
pump(
stream,
replicationStream,
stream,
(err) => {
console.log('pipe finished', err)
}
)
})
})
app.listen(PORT, (err) => {
if (err) throw err
console.log('Listening on port: ' + PORT)
})