-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
80 lines (72 loc) · 2.1 KB
/
Copy pathindex.js
File metadata and controls
80 lines (72 loc) · 2.1 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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
const webSocketsServerPort = 8000;
const webSocketServer = require("websocket").server;
const http = require("http");
const watch = require("node-watch");
const dirTree = require("directory-tree");
// Spinning the http server and the websocket server.
const server = http.createServer();
server.listen(webSocketsServerPort);
const wsServer = new webSocketServer({
httpServer: server,
});
// I keep the client connection on this object
var connection = {};
// Recover arguments passed in console
var myArgs = process.argv.slice(2);
// Returns function that updates file structure
var tree = () => dirTree(myArgs[0]);
function handleWatch() {
myArgs.forEach((arg) => {
watch(arg, { recursive: true }, function (evt, name) {
connection
? connection.send(buildObject())
: console.log("connection is not yet established");
});
});
}
function buildObject() {
var obj = { name: "", path: "", children: [] };
myArgs.forEach((arg) => {
var fileStructure = dirTree(arg);
if (fileStructure != null) {
obj.children.push(fileStructure);
}
});
return JSON.stringify(obj);
}
//This watches for changes on the file structure
try {
handleWatch();
} catch (err) {
if (myArgs[0] == null) {
console.log("You have to specify a path in the console");
} else {
console.log("Unfortunately the path you typed doesn't exist");
}
}
// This code generates unique userid for everyuser.
const getUniqueID = () => {
const s4 = () =>
Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
return s4() + s4() + "-" + s4();
};
// This handles first connection
wsServer.on("request", function (request) {
var userID = getUniqueID();
console.log(
new Date() +
" Recieved a new connection from origin " +
request.origin +
"."
);
connection = request.accept(null, request.origin);
console.log("connected: " + userID);
connection.send(buildObject());
// This closes the conection
connection.on("close", function (connection) {
console.log(new Date() + " Peer " + userID + " disconnected.");
connection = {};
});
});