Skip to content

Instantly share code, notes, and snippets.

@jonathantneal
Created November 15, 2016 23:51
Show Gist options
  • Save jonathantneal/4fc219f74d5e7b64cda89a3f9fe98e21 to your computer and use it in GitHub Desktop.
Save jonathantneal/4fc219f74d5e7b64cda89a3f9fe98e21 to your computer and use it in GitHub Desktop.
A demonstration of how simple it is to create a local server in Node

Simple Node Server

A demonstration of how simple it is to create a local server in Node.

This barebones example is here to help you understand how you could serve a simple static directory as a local site.

Usage

node .

Dependencies

This demonstration attempts to use as few dependencies as possible.

  • mime-types is used to serve the correct mime-type and charset for any file.
// tooling
const fs = require('fs');
const http = require('http');
const mime = require('mime-types');
const path = require('path');
// create a server
http.createServer((request, response) => {
// when files are requested
const onfile = (filename) => {
// read the file
fs.readFile(filename, (error, data) => error
// if an error, attempt to resolve, otherwise display the data
? error.code === 'EISDIR'
// if in a directory, read index.html, otherwise display the error
? onfile(path.join(filename, 'index.html'))
: onerror(error)
: ondata(filename, data)
);
};
// when data is received
const ondata = (filename, data) => {
// respond successfully with the file header and contents
response.writeHead(200, { 'Content-Type': mime.contentType(path.basename(filename)) });
response.end(data, mime.charset(path.basename(filename)));
};
// when errors are encountered
const onerror = (error) => {
// respond unsuccessfully with the error
response.writeHead(500, { 'Content-Type': 'text/html' });
response.end(`<h1>Error: ${ error.code }</h1><pre>${ error }</pre>`, 'utf-8');
};
// request directory/static/${ location pathname }
onfile(path.resolve(process.cwd(), 'static', request.url.slice(1)));
}).listen(8080);
{
"private": true,
"devDependencies": {
"mime-types": "^2"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment