@e22m4u/js-http-static-router 0.0.2 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -29,65 +29,51 @@ import http from 'http';
29
29
  import {HttpStaticRouter} from '@e22m4u/js-http-static-router';
30
30
 
31
31
  // создание экземпляра маршрутизатора
32
- const staticRouter = new HttpStaticRouter();
33
-
34
- // определение директории "../static"
35
- // доступной по адресу "/static"
36
- staticRouter.addRoute(
37
- '/static', // путь маршрута
38
- `${import.meta.dirname}/../static`, // файловый путь
39
- );
40
-
41
- // объявление файла "./static/file.txt"
42
- // доступным по адресу "/static"
43
- staticRouter.addRoute(
44
- '/file.txt',
45
- `${import.meta.dirname}/static/file.txt`,
46
- );
47
-
48
- // создание HTTP сервера и подключение обработчика
32
+ const staticRouter = new HttpStaticRouter({
33
+ // при использовании опции "baseDir", относительные пути
34
+ // в регистрируемых маршрутах будут разрешаться относительно
35
+ // указанного адреса файловой системы
36
+ baseDir: import.meta.dirname,
37
+ // в данном случае "baseDir" указывает
38
+ // на путь к директории текущего модуля
39
+ });
40
+ // доступ к import.meta.dirname возможен
41
+ // только для ESM начиная с Node.js 20.11.0
42
+
43
+ // экспозиция содержимого директории "/static"
44
+ // для доступа по адресу "/assets/{file_name}"
45
+ staticRouter.defineRoute({
46
+ remotePath: '/assets', // путь маршрута
47
+ resourcePath: '../static', // файловый путь
48
+ });
49
+
50
+ // объявление файла "./index.html"
51
+ // для доступа по адресу "/home"
52
+ staticRouter.defineRoute({
53
+ remotePath: '/home',
54
+ resourcePath: './static/index.html',
55
+ });
56
+
57
+ // создание HTTP сервера и определение
58
+ // функции для обработки запросов
49
59
  const server = new http.Server();
50
- server.on('request', (req, res) => {
51
- // если статический маршрут найден,
52
- // выполняется поиск и отдача файла
53
- const staticRoute = staticRouter.matchRoute(req);
54
- if (staticRoute) {
55
- return staticRouter.sendFileByRoute(staticRoute, req, res);
60
+ server.on('request', async (req, res) => {
61
+ const fileSent = await staticRouter.handleRequest(req, res);
62
+ if (!fileSent) {
63
+ res.writeHead(404, {'Content-Type': 'text/plain'});
64
+ res.write('404 Not Found');
65
+ res.end();
56
66
  }
57
- // в противном случае запрос обрабатывается
58
- // основной логикой приложения
59
- res.writeHead(200, {'Content-Type': 'text/plain'});
60
- res.end('Hello from App!');
61
67
  });
62
68
 
63
69
  server.listen(3000, () => {
64
70
  console.log('Server is running on http://localhost:3000');
65
71
  console.log('Try to open:');
66
- console.log('http://localhost:3000/static/');
67
- console.log('http://localhost:3000/file.txt');
72
+ console.log('http://localhost:3000/home');
73
+ console.log('http://localhost:3000/assets/file.txt');
68
74
  });
69
75
  ```
70
76
 
71
- ### trailingSlash
72
-
73
- Так как в HTML обычно используются относительные пути, чтобы файлы
74
- стилей и изображений загружались относительно текущего уровня вложенности,
75
- а не обращались на уровень выше, может потребоваться параметр `trailingSlash`
76
- для принудительного добавления косой черты в конце адреса.
77
-
78
- ```js
79
- import http from 'http';
80
- import {HttpStaticRouter} from '@e22m4u/js-http-static-router';
81
-
82
- const staticRouter = new HttpStaticRouter({
83
- trailingSlash: true, // <= добавлять косую черту (для директорий)
84
- });
85
-
86
- // теперь, при обращении к директориям без закрывающего
87
- // слеша будет выполняться принудительный редирект (302)
88
- // /dir => /dir/
89
- ```
90
-
91
77
  ## Тесты
92
78
 
93
79
  ```bash