Skip to content

Instantly share code, notes, and snippets.

@luveti
Last active August 29, 2015 14:07
Show Gist options
  • Save luveti/2fad3f094defebad3006 to your computer and use it in GitHub Desktop.
Save luveti/2fad3f094defebad3006 to your computer and use it in GitHub Desktop.
A small nodejs web server with support for evaluating javascript files in a way similar to php (files with .jss extension). This server can be run as-is without needing to install any additional packages. To run type: nodejs "server.js" "/path/to/root/folder/" "port"
var sys = require('sys'), url = require("url"), path = require("path"), fs = require("fs"),
querystring = require("querystring"), folder = "/", port = process.argv[3] || 25565;
var server = require("http").createServer(HTTP_Server).listen(parseInt(port, 10));
function HTTP_ProcessPost(request, response, callback) {
var queryData = "";
if(typeof callback !== 'function') return null;
if(request.method == 'POST') {
request.on('data', function(data) {
queryData += data;
if(queryData.length > 1e6) {
queryData = "";
response.writeHead(413, {'Content-Type': 'text/plain'}).end();
request.connection.destroy();
}
});
request.on('end', function() {
response.post = querystring.parse(queryData);
callback();
});
} else {
response.writeHead(405, {'Content-Type': 'text/plain'});
response.end();
}
}
function HTTP_HandleRequest(response, values, filename, filetype){
fs.readFile(filename, 'binary', function(err, file) {
if(err) {
response.writeHead(500, {"Content-Type": "text/plain"});
response.write(err + "\n");
response.end();
return;
}
response.writeHead(200);
if(filetype == 'jss'){
//process the file
try{
eval('(function(response, values){' + file + '}(response, values));');
}catch(e){
response.write('Error running "' + filename + '": ' + e, "binary");
response.end();
}
}else{
//send the file
response.write(file, "binary");
response.end();
}
});
}
function HTTP_Server(request, response) {
var url_parts = url.parse(request.url, true);
var uri = url_parts.pathname, filename = path.join(folder, uri);
var values = url_parts.query;
var fileChunks = filename.split('/');
var filetype = fileChunks[fileChunks.length - 1].split('.')[1];
fs.exists(filename, function(exists) {
if(!exists) {
response.writeHead(404, {"Content-Type": "text/plain"});
response.write("404 Not Found\n");
response.end();
return;
}
//Give them the index file of that directory
if(fs.statSync(filename).isDirectory()) filename += '/index.html';
if(request.method == 'POST'){
HTTP_ProcessPost(request, response, function(){
HTTP_HandleRequest(response, response.post, filename, filetype);
});
}else{
HTTP_HandleRequest(response, values, filename, filetype);
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment