-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathindex.js
More file actions
43 lines (34 loc) · 1.07 KB
/
index.js
File metadata and controls
43 lines (34 loc) · 1.07 KB
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
const fs = require("fs")
const http = require("http")
const socketIo = require("socket.io")
const PORT = 4000
let body =
"# Welcome to Litepad\n\nA minimalist real-time collaborative editor.\nStart typing — changes sync instantly with everyone connected."
const handler = (req, res) => {
fs.readFile(`${__dirname}/index.html`, (error, data) => {
if (error) {
res.writeHead(500)
return res.end("Error loading index.html")
}
res.writeHead(200)
return res.end(data)
})
}
const app = http.createServer(handler)
const io = socketIo.listen(app)
app.listen(PORT)
console.log(`Litepad running at port ${PORT}`)
io.sockets.on("connection", (socket) => {
// Keep newly joined clients synchronized with the shared editor state.
socket.emit("refresh", { body })
socket.on("refresh", (nextBody) => {
body = nextBody
})
socket.on("change", (op) => {
const isUserInputChange =
op.origin === "+input" || op.origin === "paste" || op.origin === "+delete"
if (isUserInputChange) {
socket.broadcast.emit("change", op)
}
})
})