uptime-example.js 1.3 KB

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