server.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536
  1. const express = require('express');
  2. const { exec } = require('child_process');
  3. const path = require('path');
  4. const app = express();
  5. const ALLOWED_INTERFACES = ['eth0', 'wlan0', 'docker0', 'tailscale0'];
  6. const FRONTEND_DIR = process.env.FRONTEND_DIR || 'frontend-build';
  7. app.use(express.static(path.join(__dirname, '..', FRONTEND_DIR)));
  8. app.get('/api/vnstat/:iface', (req, res) => {
  9. const iface = req.params.iface;
  10. if (!ALLOWED_INTERFACES.includes(iface)) {
  11. return res.status(400).json({ error: 'Invalid interface' });
  12. }
  13. exec(`vnstat -i ${iface} --json`, (error, stdout, stderr) => {
  14. if (error) {
  15. return res.status(500).json({ error: stderr || error.message });
  16. }
  17. try {
  18. const data = JSON.parse(stdout);
  19. res.json(data);
  20. } catch (e) {
  21. res.status(500).json({ error: 'Failed to parse vnstat output.' });
  22. }
  23. });
  24. });
  25. // Serve React frontend for all non-API routes
  26. app.get('*', (req, res) => {
  27. res.sendFile(path.join(__dirname, '..', FRONTEND_DIR, 'index.html'));
  28. });
  29. const PORT = process.env.PORT || 3001;
  30. app.listen(PORT, () => console.log(`Server running on port ${PORT}`));