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

e22m4u ebdaa9c32b chore: bumps version to 0.0.1 10 часов назад
.husky d4c4ea6fed chore: initial commit 10 часов назад
dist 17b016960e chore: updates README.md 10 часов назад
example d4c4ea6fed chore: initial commit 10 часов назад
src d4c4ea6fed chore: initial commit 10 часов назад
.c8rc d4c4ea6fed chore: initial commit 10 часов назад
.commitlintrc d4c4ea6fed chore: initial commit 10 часов назад
.editorconfig d4c4ea6fed chore: initial commit 10 часов назад
.gitignore d4c4ea6fed chore: initial commit 10 часов назад
.mocharc.json d4c4ea6fed chore: initial commit 10 часов назад
.prettierrc d4c4ea6fed chore: initial commit 10 часов назад
LICENSE d4c4ea6fed chore: initial commit 10 часов назад
README.md 17b016960e chore: updates README.md 10 часов назад
build-cjs.js d4c4ea6fed chore: initial commit 10 часов назад
eslint.config.js d4c4ea6fed chore: initial commit 10 часов назад
package.json ebdaa9c32b chore: bumps version to 0.0.1 10 часов назад
tsconfig.json d4c4ea6fed chore: initial commit 10 часов назад

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');
});

Тесты

npm run test

Лицензия

MIT