-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
60 lines (48 loc) · 1.16 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
54
55
56
57
58
59
60
var http = require("http");
var url = require("url");
var fs = require("fs");
var watchr = require("watchr");
var socketIO = require("socket.io");
var PORT = 13337;
if (!process.argv[2]) {
log("Usage: web-reloader path/to/directory/to/watch");
process.exit();
}
var directory = process.argv[2];
var server = http.createServer(onRequest);
var io = socketIO(server);
io.on("connection", function(socket) {
var ip = socket.request.connection.remoteAddress;
log("New client (" + ip + ")");
socket.on("disconnect", function() {
log("Lost client (" + ip + ")");
});
});
log("Starting server on port " + PORT)
server.listen(PORT);
watchr.watch({
path: directory,
catchupDelay: 100,
listener: function (f, curr, prev) {
console.log("Detected change");
sendRefresh();
}
});
function onRequest(request, response) {
var requestUrl = url.parse(request.url);
switch (requestUrl.pathname) {
case "/refresh":
sendRefresh();
break;
case "/":
fs.createReadStream(__dirname + "/public/client.js").pipe(response);
break;
}
}
function sendRefresh() {
log("Send refresh");
io.emit("reload", {});
}
function log() {
console.log.apply(console, arguments);
}