68 lines
1.7 KiB
JavaScript
68 lines
1.7 KiB
JavaScript
// server.js
|
|
require('dotenv').config();
|
|
const express = require('express');
|
|
const path = require('path');
|
|
const morgan = require('morgan');
|
|
const bodyParser = require('body-parser');
|
|
const http = require('http');
|
|
const WebSocket = require('ws');
|
|
const { spawn } = require('child_process');
|
|
|
|
const indexRouter = require('./routes/index');
|
|
|
|
const app = express();
|
|
const PORT = process.env.PORT || 3000;
|
|
|
|
// View engine
|
|
app.set('view engine', 'ejs');
|
|
app.set('views', path.join(__dirname, 'views'));
|
|
|
|
// Middleware
|
|
app.use(express.static(path.join(__dirname, 'public')));
|
|
app.use(bodyParser.urlencoded({ extended: true }));
|
|
app.use(bodyParser.json());
|
|
|
|
// Morgan: log only non-static requests
|
|
// app.use(morgan(':method :url :status :res[content-length] - :response-time ms', {
|
|
// skip: (req) => req.url.startsWith('/assets') || req.url.startsWith('/favicon.ico')
|
|
// }));
|
|
|
|
// Routes
|
|
app.use('/', indexRouter);
|
|
|
|
// Error handler
|
|
app.use((err, req, res, next) => {
|
|
console.error(err);
|
|
res.status(500).render('error', {
|
|
message: 'Internal Server Error',
|
|
detail: err.message
|
|
});
|
|
});
|
|
|
|
// -----------------------------
|
|
// Wrap Express in HTTP + WS
|
|
// -----------------------------
|
|
const server = http.createServer(app);
|
|
const wss = new WebSocket.Server({ server });
|
|
|
|
// When a client connects, stream PM2 logs
|
|
wss.on('connection', ws => {
|
|
const pm2Logs = spawn('pm2', ['logs', '--json']);
|
|
|
|
pm2Logs.stdout.on('data', data => {
|
|
ws.send(data.toString());
|
|
});
|
|
|
|
pm2Logs.stderr.on('data', data => {
|
|
ws.send('ERROR: ' + data.toString());
|
|
});
|
|
|
|
ws.on('close', () => {
|
|
pm2Logs.kill();
|
|
});
|
|
});
|
|
|
|
server.listen(PORT, () =>
|
|
console.log(`Proxer-Downloader running on http://localhost:${PORT}`)
|
|
);
|