Skip to content

Instantly share code, notes, and snippets.

@brianswisher
Last active December 10, 2015 07:48
Show Gist options
  • Save brianswisher/4403415 to your computer and use it in GitHub Desktop.
Save brianswisher/4403415 to your computer and use it in GitHub Desktop.
Zero dependency static node server w/ form post handler. Form posts to "/" will echo submitted values in JSON.
var http = require('http'),
querystring = require('querystring'),
url = require( "url" ),
path = require( "path" ),
fs = require( "fs" );
module.exports = http.createServer(function (req, res) {
var code = 404,
uri = url.parse( req.url ).pathname,
filename = path.join(process.cwd(), uri),
ext = filename.split('.').pop(),
mimeType,
cType = function(type) {
return {"Content-Type": type};
},
reqLog = function(code, method, url){
console.log("["+code+"] " + method + " to " + url);
},
notFound = function(code, req, res, mssg){
reqLog(code, req.method, req.url);
res.writeHead(code, "Not found", cType("text/html"));
res.end('<html><head><title>'+code+' - '+mssg+'</title></head><body><h1>'+mssg+'.</h1></body><html>');
},
error = function(code, req, res, err) {
res.writeHead( 500, cType("text/plain") );
res.write(err + "\n");
res.end();
},
getFile = function(code, req, res, mimeType, file) {
res.writeHead( 200, mimeType );
res.write( file, "binary" );
res.end();
},
getJson = function(code, req, res){
reqLog(code, req.method, req.url);
var data = '';
req.on('data', function(chunk) { data += chunk; });
req.on('end', function() {
res.writeHead(code, "OK", cType("application/json"));
console.log('[data]', data);
if ( data.indexOf('{') > -1 && data.indexOf('}') > 0 ) {
res.end(data);
} else {
res.end(JSON.stringify( querystring.parse(data) ));
}
});
};
switch(req.url) {
case '/':
if (req.method.toLowerCase() === 'post') {
getJson(200, req, res);
break;
}
default:
if ( ext === 'js' ) {
mimeType = cType("application/javascript");
} else if ( ext === 'css' ) {
mimeType = cType("text/css");
}
fs.exists( filename, function( exists ) {
if ( !exists ) {
notFound(code, req, res, 'Not found');
} else {
if ( fs.statSync( filename ).isDirectory() ) filename += '/index.html';
fs.readFile( filename, "binary", function( err, file ) {
if ( err ) {
error(500, req, res, err);
} else {
getFile(200, req, res, mimeType, file);
}
});
}
});
}
}).listen(1234, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1234/');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment