HTTP-маршрутизатор статичных ресурсов для Node.js

e22m4u 3ef2e6fc57 docs: updates README.md 1 час назад
.husky d4c4ea6fed chore: initial commit 4 часов назад
dist ac1c705e9e feat: adds "trailingSlash" option 1 час назад
example ac1c705e9e feat: adds "trailingSlash" option 1 час назад
src ac1c705e9e feat: adds "trailingSlash" option 1 час назад
.c8rc d4c4ea6fed chore: initial commit 4 часов назад
.commitlintrc d4c4ea6fed chore: initial commit 4 часов назад
.editorconfig d4c4ea6fed chore: initial commit 4 часов назад
.gitignore d4c4ea6fed chore: initial commit 4 часов назад
.mocharc.json d4c4ea6fed chore: initial commit 4 часов назад
.prettierrc d4c4ea6fed chore: initial commit 4 часов назад
LICENSE d4c4ea6fed chore: initial commit 4 часов назад
README.md 3ef2e6fc57 docs: updates README.md 1 час назад
build-cjs.js d4c4ea6fed chore: initial commit 4 часов назад
eslint.config.js d4c4ea6fed chore: initial commit 4 часов назад
package.json ac1c705e9e feat: adds "trailingSlash" option 1 час назад
tsconfig.json d4c4ea6fed chore: initial commit 4 часов назад

README.md

@e22m4u/js-http-static-router

HTTP-маршрутизатор статичных ресурсов для Node.js.

Установка

npm install @e22m4u/js-http-static-router

Модуль поддерживает ESM и CommonJS стандарты.

ESM

import {HttpStaticRouter} from '@e22m4u/js-http-static-router';

CommonJS

const {HttpStaticRouter} = require('@e22m4u/js-http-static-router');

Использование

import http from 'http';
import {HttpStaticRouter} from '@e22m4u/js-http-static-router';

// создание экземпляра маршрутизатора
const staticRouter = new HttpStaticRouter();

// определение директории "../static"
// доступной по адресу "/static"
staticRouter.addRoute(
  '/static',                          // путь маршрута
  `${import.meta.dirname}/../static`, // файловый путь
);

// объявление файла "./static/file.txt"
// доступным по адресу "/static"
staticRouter.addRoute(
  '/file.txt',
  `${import.meta.dirname}/static/file.txt`,
);

// создание HTTP сервера и подключение обработчика
const server = new http.Server();
server.on('request', (req, res) => {
  // если статический маршрут найден,
  // выполняется поиск и отдача файла
  const staticRoute = staticRouter.matchRoute(req);
  if (staticRoute) {
    return staticRouter.sendFileByRoute(staticRoute, req, res);
  }
  // в противном случае запрос обрабатывается
  // основной логикой приложения
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello from App!');
});

server.listen(3000, () => {
  console.log('Server is running on http://localhost:3000');
  console.log('Try to open:');
  console.log('http://localhost:3000/static/');
  console.log('http://localhost:3000/file.txt');
});

trailingSlash

Так как в HTML обычно используются относительные пути, чтобы файлы стилей и изображений загружались относительно текущего уровня вложенности, а не обращались на уровень выше, может потребоваться параметр trailingSlash для принудительного добавления косой черты в конце адреса.

import http from 'http';
import {HttpStaticRouter} from '@e22m4u/js-http-static-router';

const staticRouter = new HttpStaticRouter({
  trailingSlash: true, // <= добавлять косую черту (для директорий)
});

// теперь при обращении к директориям без закрывающего
// слеша будет выполняться принудительный редирект (302)
// /dir => /dir/

Тесты

npm run test

Лицензия

MIT