-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
executable file
·98 lines (80 loc) · 2.16 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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
#!/usr/bin/env node
const http = require('http');
const fs = require("fs");
const express = require('express');
const socketio = require('socket.io');
const FileWatcher = require('./FileWatcher');
function getFileNameFromCommandLine() {
return process.argv[2];
}
function getPortFromCommandLine() {
return process.argv[3];
}
function createApp() {
const app = express();
const httpServer = http.createServer(app);
const io = socketio(httpServer);
return {
app,
httpServer,
io
};
}
function isFilePresent(path) {
try {
const data = fs.statSync(path);
return true;
}catch(e) {
const message = `File not present error: ${path} is not present
Please provide a valid path
`;
process.stderr.write(message);
process.exit(1);
}
}
const fileName = getFileNameFromCommandLine();
if(isFilePresent(fileName)){
bootstrap(fileName);
}
function bootstrap(fileName){
const fileWatcher = new FileWatcher(fileName);
const { app, httpServer, io } = createApp();
attachRoute(app);
attachIOHandler(io, { fileName });
startApp(httpServer);
fileWatcher.attachListener((line) => {
io.emit('logline', line);
});
fileWatcher.start();
}
function attachRoute(app) {
app.get('/', (req, res) => {
res.sendFile(__dirname + '/public/index.html');
});
}
function attachIOHandler(io, meta) {
io.on('connection', function(socket) {
console.log('Client connected with id', socket.id);
socket.emit('filename', meta.fileName);
socket.on('disconnect', function(){
console.log('user disconnected');
});
});
}
function startApp(httpServer) {
const port = getPortFromCommandLine() || 3000;
httpServer.listen(port, (err) => {
if(err) {
console.log(err.message);
} else {
console.log(`Started server at http://localhost:${port}`);
}
});
}
// Usage :
// (async function run() {
// const fileName = getFileNameFromCommandLine();
// if(!fileName) return;
// const fileWatcher = new FileWatcher(fileName);
// fileWatcher.start();
// })();