Skip to content

Instantly share code, notes, and snippets.

@joyrexus
Last active January 4, 2016 13:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joyrexus/8626919 to your computer and use it in GitHub Desktop.
Save joyrexus/8626919 to your computer and use it in GitHub Desktop.
Simple http server, dependency free

A simple, dependency-free http server to serve files relative to your current working directory.

Install the serve command with npm -g install.

Use serve [PORT] to start serving files in the current directory via the specified port number (default is 3000).

Open http://localhost:3000/ to view your web pages.

See Also

{createServer} = require 'http'
fs = require 'fs'
path = require 'path'
port = process.argv[2] or 3000
server = (req, res) ->
console.log 'starting req ...'
file = '.' + req.url
file = './index.html' if file is './'
extname = path.extname file
contentType = 'text/html'
switch extname
when '.js' then contentType = 'text/javascript'
when '.css' then contentType = 'text/css'
read = (err, content) ->
if err
res.writeHead 500
res.end()
else
res.writeHead(200, 'Content-Type': contentType)
res.end content, 'utf-8'
respond = (exists) ->
if exists
fs.readFile(file, read)
else
res.writeHead 404
res.end()
fs.exists(file, respond)
createServer(server).listen(port)
console.log 'server running at http://localhost:' + port
<!DOCTYPE html>
<meta charset="utf-8">
<style>
body {
font-family: 'Helvetica Neue';
font-weight: 100;
font-size: 200px;
margin: 20px;
color: #777;
}
</style>
<div>It worked!</div>
(function() {
var createServer, fs, path, port, server;
createServer = require('http').createServer;
fs = require('fs');
path = require('path');
port = process.argv[2] || 3000;
server = function(req, res) {
var contentType, extname, file, read, respond;
console.log('starting req ...');
file = '.' + req.url;
if (file === './') {
file = './index.html';
}
extname = path.extname(file);
contentType = 'text/html';
switch (extname) {
case '.js':
contentType = 'text/javascript';
break;
case '.css':
contentType = 'text/css';
}
read = function(err, content) {
if (err) {
res.writeHead(500);
res.end();
} else {
res.writeHead(200, { 'Content-Type': contentType });
res.end(content, 'utf-8');
}
};
respond = function(exists) {
if (exists) {
fs.readFile(file, read);
} else {
res.writeHead(404);
res.end();
}
};
fs.exists(file, respond);
};
createServer(server).listen(port);
console.log('server running at http://localhost:' + port);
}).call(this);
{
"name": "http-server",
"version": "0.0.1",
"description": "A simple http server.",
"main": "index.js",
"scripts": {
"start": "node index.js"
},
"bin": {
"serve": "./index.js"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment