-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
executable file
·95 lines (79 loc) · 2.19 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
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
// Express server with socketio for real-time communication
// Import modules
import express from 'express';
import http from 'http';
import { Server } from "socket.io";
import path from 'path';
import fs from 'fs';
import Chokidar from 'chokidar';
const __dirname = import.meta.dirname;
// Dotenv
import dotenv from 'dotenv';
dotenv.config();
// CONF
const PORT = process.env.PORT || 3000;
const MEDIA = process.env.MEDIA || path.join(__dirname, 'media');
// Creating express app
const app = express();
const server = http.createServer(app);
const io = new Server(server);
// Last media
let lastMedia = null;
// find newest file in MEDIA recursive
let newestFileTime = 0;
let newestFile = null;
function findNewestFile(dir) {
fs.readdirSync(dir).forEach(file => {
let fullPath = path.join(dir, file);
let stat = fs.statSync(fullPath);
if (stat.isDirectory()) {
findNewestFile(fullPath);
} else {
if (stat.mtimeMs > newestFileTime) {
newestFileTime = stat.mtimeMs;
newestFile = fullPath;
}
}
});
}
findNewestFile(MEDIA);
if (newestFile) {
lastMedia = path.relative(MEDIA, newestFile);
console.log('Last media:', lastMedia);
}
// Setting up static www and media folders
app.use(express.static(path.join(__dirname, 'www')));
// static /media
app.use('/media', express.static(MEDIA));
// Routes
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'www/index.html'));
});
// Socket.io
io.on('connection', (socket) => {
console.log('New WebView connection');
// Send last media
if (lastMedia) {
socket.emit('new', lastMedia);
}
});
// Watch folder for changes (recursive) using Chokidar
const watcher = Chokidar.watch(MEDIA, {
ignored: /(^|[\/\\])\../,
persistent: true,
ignoreInitial: true,
awaitWriteFinish: {
stabilityThreshold: 200,
pollInterval: 100
}
});
watcher.on('all', (event, path) => {
console.log(event, path);
let relPath = path.replace(MEDIA, '');
lastMedia = relPath;
io.emit('new', relPath);
});
// Starting server
server.listen(PORT, () => {
console.log(`StableView running on port ${PORT}`);
});