Skip to content

HttpStaticSite

do- edited this page Sep 3, 2024 · 17 revisions

HttpStaticSite is a tiny web server publishing the static content of a given root directory.

It is merely a demo for HttpRequestContext, by no means intended for use in any production environment.

Only static content is published. Directories are presented by index files, no listing is implemented.

Content-Type and Content-Length are set based on file name and size respectively, no other HTTP header is added.

Usage

const {HttpStaticSite} = require ('http-server-tools')

const mySite = new HttpStaticSite ({
   root : '/~/my-site/document-root',
// index: 'index.html',
})

http.createServer ({/**/})
  .on ('request', (_, response) => mySite.handle (response).then (
    ()  => (), 
    err => console.log (err.path ? `File not found: ${err.path}` : err)
  ))
  .listen ({host: '127.0.0.1', port: 8000})

Methods

This top level asynchronous method is to be called from an http.Server directly or through some router.

For a given ServerResponse response, it writes therein the HTTP message based on this.getStream (this.getFilePath (response.req.url)) (see below).

The result, normally, is undefined.

The first error occurred, is both written into the response (if possible) and thrown up from the method.

For a given url, it returns the corresponding absolute file path under this.root.

If the path correnponds to a directory, index file is used instead.

If the file doesn't exist, an error is thrown (see below)

Throws a 404 http error with additional path field unless the path is not found in the file system. Otherwise, does nothing.

For a given absolute file path, it returns the corresponding stream.Readable fith the additional [HttpRequestContext.CONTENT_TYPE] field set.

For a given file path, it returns the corresponding Content-Type using mime-db.

Clone this wiki locally