uptime-example.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. import http from 'http';
  2. import {TrieRouter} from '../src/index.js';
  3. import {HttpMethod} from '../src/route.js';
  4. const router = new TrieRouter();
  5. // регистрация маршрута для вывода
  6. // времени работы сервера
  7. router.defineRoute({
  8. method: HttpMethod.GET,
  9. path: '/',
  10. handler() {
  11. const uptimeSec = process.uptime();
  12. const days = Math.floor(uptimeSec / (60 * 60 * 24));
  13. const hours = Math.floor((uptimeSec / (60 * 60)) % 24);
  14. const mins = Math.floor((uptimeSec / 60) % 60);
  15. const secs = Math.floor(uptimeSec % 60);
  16. let res = 'Uptime';
  17. if (days) res += ` ${days}d`;
  18. if (days || hours) res += ` ${hours}h`;
  19. if (days || hours || mins) res += ` ${mins}m`;
  20. res += ` ${secs}s`;
  21. return res;
  22. },
  23. })
  24. // создание экземпляра HTTP сервера
  25. // и подключение обработчика запросов
  26. const server = new http.Server();
  27. server.on('request', router.requestListener);
  28. // прослушивание входящих запросов
  29. // на указанный адрес и порт
  30. const port = 3000;
  31. const host = '0.0.0.0';
  32. server.listen(port, host, function () {
  33. const cyan = '\x1b[36m%s\x1b[0m';
  34. console.log(cyan, 'Server listening on port:', port);
  35. console.log(cyan, 'Open in browser:', `http://${host}:${port}`);
  36. });