Created
November 7, 2012 21:39
-
-
Save Cacodaimon/4034675 to your computer and use it in GitHub Desktop.
A minimalistic http server for serving static files with Node.js. Used @ cacodaemon.de
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* A minimalistic http server for serving static files with Node.js. | |
* Don't use this in a production enviroment, this http server is not fast or secure! | |
* | |
* Autor: Guido Krömer <[email protected]> | |
* Page: www.cacodaemon.de | |
* Date: 2012-11-07 | |
*/ | |
module.exports.MiniHttp = function (path, port, ip, indexPage) { | |
var path = path; | |
var port = port ? port : 8000; | |
var ip = ip ? ip : null; | |
var indexPage = indexPage ? indexPage : 'index.html'; | |
var http = require('http'); | |
var fs = require('fs'); | |
var mime = new Array(); | |
mime.css = 'text/css'; | |
mime.html = 'text/html'; | |
mime.js = 'text/javascript'; | |
mime.jpg = 'image/jpeg'; | |
mime.jpeg = 'image/jpeg'; | |
mime.jpe = 'image/jpeg'; | |
mime.gif = 'image/gif'; | |
mime.png = 'image/png'; | |
mime.svg = 'image/svg+xml'; | |
mime.svgz = 'image/svg+xml'; | |
var four0Four = '<!doctype html><html><head><title>404</title></head><body><h2>File: __FILE__ not found!</h2></body></html>'; | |
this.addMime = function (extension, type) { | |
mime[extension] = type; | |
} | |
http.createServer(function (request, response) { | |
if (request.url == '/') { | |
request.url = indexPage; | |
} | |
var fileType = request.url.substr(request.url.lastIndexOf('.') + 1); | |
console.log(request.url); | |
fs.readFile(path + request.url, function (err, data) { | |
if (err) { | |
response.writeHead(404, {'Content-Type': 'text/html'}); | |
response.end(four0Four.replace('__FILE__', request.url)); | |
} | |
else if (data) { | |
response.writeHead(200, {'Content-Type': mime[fileType]}); | |
response.end(data); | |
} | |
}); | |
}).listen(port, ip); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var MiniHttp = require('./MiniHttp.js').MiniHttp; | |
var server = new MiniHttp('/tmp/', 8000, null, 'foo.html'); | |
server.addMime('pdf', 'application/pdf'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment