-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
50 lines (43 loc) · 1.33 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
const app = require('express')();
const http = require('http').Server(app);
const io = require('socket.io')(http);
const fsWrapper = require('./fsWrapper');
const actions = require('./src/actions/files');
// send action to clear all files
let clearAllFiles = (client) => {
client.emit('fileActions', actions.clearFilesAction());
};
// iterate through all existing files and send action to add each one to client
let sendUpdatedListOfFiles = (client) => {
fsWrapper.readDirectory((files) => {
files.map((file) => {
client.emit('fileActions', actions.fileCreatedAction(file));
});
});
};
// listen for new connections
io.on('connection', (client) => {
// send clear files and send updated list
clearAllFiles(client);
sendUpdatedListOfFiles(client);
// listen for actions from the client
client.on('fileActions', (action) => {
if (action.type === 'CREATE_FILE') {
fsWrapper.createNewFile(action.filename);
}
})
});
// watch the directory for changes and send action via WS
fsWrapper.watch((changeType, filename) => {
switch (changeType) {
case 'create':
io.emit('fileActions', actions.fileCreatedAction(filename));
break;
case 'remove':
io.emit('fileActions', actions.fileRemovedAction(filename));
break;
}
});
http.listen(3001, () => {
console.log('listening on *:3001');
});