1.1.0 • Published 5 months ago

http-simple-serve v1.1.0

Weekly downloads
-
License
MIT
Repository
github
Last release
5 months ago

http-simple-serve

⚙️ Simple HTTP server for use with static resources.

Test Lint Build NPM Version Documentation

Install

$ npm install http-simple-serve

Usage

import http from 'http-simple-serve';

http({
  port: process.env.PORT ? parseInt(process.env.PORT) : 8080,
  root: 'public/',
  entry: 'index.html',
});

Custom Server

import { readFileSync } from 'node:fs';
import { createServer } from 'node:http';

import { readStaticAssetsSync, tryParseUrl } from 'http-simple-serve';

const staticFiles = readStaticAssetsSync('./public', 'index.html');

createServer(async (req, res) => {
  try {
    const url = tryParseUrl(req.url);

    if (Object.keys(staticFiles).includes(url)) {
      const { path, contentType } = staticFiles[url];

      const content = readFileSync(path);

      res.setHeader('Content-type', contentType);

      res.writeHead(200);

      res.end(content);
    } else if (url === '/robots.txt') {
      res.writeHead(200);

      res.end('User-agent: *\nAllow: /');
    } else {
      res.writeHead(404);

      res.end('Not found');
    }
  } catch (error) {
    res.writeHead(500);

    res.end('Internal server error');
  }
}).listen(process.env.PORT ? parseInt(process.env.PORT) : 8080);

Debugging

This will output all requests to the console with the path and response status code.

$ NODE_ENV=development npm start
1.1.0

5 months ago

1.0.0

6 months ago