-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
executable file
·66 lines (50 loc) · 1.51 KB
/
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
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
#!/usr/bin/env node
const chokidar = require("chokidar");
const createIO = require("socket.io");
const debug = require("debug")("cli");
const express = require("express");
const fs = require("fs");
const getPort = require("get-port");
const http = require("http");
const path = require("path");
const { argv } = require("yargs");
const port = argv.port || process.env.PORT || 3000;
const file = argv._ && argv._[0];
if (!file) {
debug({ argv });
console.log("pass filename as argument");
process.exit(0);
}
const start = ({ port, file }) => {
const app = express();
const server = http.createServer(app);
const io = createIO(server);
const sockets = {};
const emitContent = id => {
const content = fs.readFileSync(file, { encoding: "utf8" });
const fileName = path.basename(file);
const doEmit = id => {
sockets[id].emit("content", content);
sockets[id].emit("fileName", fileName);
};
if (id) {
doEmit(id);
} else {
Object.keys(sockets).forEach(id => doEmit(id));
}
};
chokidar.watch(file).on("change", () => {
debug("file updated, pushing to client(s)");
emitContent();
});
io.on("connection", socket => {
const { id } = socket;
sockets[id] = socket;
emitContent(id);
socket.on("disconnect", () => delete sockets[id]);
});
app.use(express.static(path.join(__dirname, "public")));
server.listen(port);
console.log(`editable-cli running on: http://localhost:${port}/`);
};
getPort({ port }).then(port => start({ port, file }));