After writing plenty of boiler plate server code every time I wanted to play around with Node.js I distilled the basic minimum, plus alpha, into a relatively practical little server that handles stuff with little overhead both code-wise and runtime-wise.
Of course it lacks lots of bell & whistle, but its simple, less than 100 lines and “good enough” for playing around
https://gist.github.com/1429248
var simpleServer = require('simpleServer');
simpleServer({
tiemout : 1000,
router : {
hello : {
world : function( data, client ) {
client.reply( null, { you : data.name } );
},
},
generic : {
handle : function( data, client ) {
console.log( client.path, data );
client.reply( null, {
path : client.path,
data : data
});
},
},
},
}).listen( 1337 );
Now point to http://localhost:1337/hello/world?name=Nodelina
and you’ll get the following back
[null,{"you":"Nodelina"}]
Also has ways to handle more interesting paths like http://localhost:1337/generic/blog/get?id=12345
[null,{ path: [ 'generic', 'blog', 'get' ], data: { id: '12345' } }]
And here is the Server code
var http = require('http');
var url = require('url');
var assert = require('assert');
module.exports = function ( options ) {
assert.ok( options.router, 'must define a router object' );
var router = options.router;
var host = options.host || '0.0.0.0';
var port = options.port || 80;
var timeout= options.timeout || 3000;
var logger = options.logger || function( err, answer, client ) {
var errMsg;
if ( err ) {
console.error( err.stack || err.message || errMsg );
errMsg = 'server error';
}
var end = new Date();
var dateformat = require('dateformat');
console.log(
dateformat( end, 'HH:MM:ss.l'),
client.url,
(errMsg && errMsg.replace(/\s+/g, '_')) || true,
end.getTime() - client.timestamp,
answer
);
}
reply = function( err, answer ) {
clearTimeout( this.timerId );
this.res.end( JSON.stringify([err && (err.message || err), answer]), 'utf8' );
logger( err, answer, this );
}
return http.createServer( function handleRequest( req, res ) {
try {
req.res = res;
req.timestamp = new Date().getTime();
var query = url.parse(req.url, true);
req.query = query;
var pathSet = query.pathname.split('/');
query.pathSet = pathSet;
req.reply = reply;
req.timerId = setTimeout( req.reply, timeout, new Error( 'server timeout' ) );
var route = router;
for( var r in pathSet ) {
var step = route[pathSet[r]];
if ( typeof step === "object" ) {
if ( step.handle ) {
return step.handle( req.query.query, req );
}
route = step;
} else if ( typeof step === "function" ) {
return step( req.query.query, req );
}
}
req.reply( new Error('server unhandled request') );
} catch ( err ) {
console.log( err.stack || err.message || err );
req.reply( new Error('server error') );
}
});
}



Game Center
