Skip to content

Instantly share code, notes, and snippets.

@timotta
Created July 17, 2012 17:18
Show Gist options
  • Save timotta/3130658 to your computer and use it in GitHub Desktop.
Save timotta/3130658 to your computer and use it in GitHub Desktop.
Node js tutorial
var dgram = require("dgram");
var fs = require("fs");
var http = require("http");
var udp = dgram.createSocket("udp4");
var buf = new Buffer("ping");
udp.send(buf, 0, 4, 42, '10.10.26.62');
console.log("pinged the object");
var controllers = {
index:function(req, res) {
res.write("hello from planet oscon - im from Brasil");
res.end();
},
message:function(req, res) {
var file = fs.createWriteStream("dump");
req.on('data', function(data){
file.write(data);
});
req.on('end', function() {
file.end();
res.end('ok');
console.log('message received');
});
},
http_proxy:function(req, res) {
req.url.replace(/\/*\/http:\/\/(.*?)\/(.*)/,function(x, host, path){
var params = {host:host, port:80, path: "/" + path};
http.get(params, function(http_res){
http_res.pipe(res);
}).on('error',function(e){
console.log("something bad happened: ", e);
});
});
}
}
var Routes = function(req, res) {
this.req = req;
this.res = res;
}
Routes.prototype = {
handle:function() {
switch(this.req.url) {
case '/':
controllers.index(this.req, this.res);
break;
case '/message':
controllers.message(this.req, this.res);
break;
default:
this.handle_patterns();
}
},
handle_patterns:function() {
if( this.req.url.indexOf("/*") == 0 ) {
controllers.http_proxy(this.req, this.res);
} else {
res.writeHead(404);
res.end()
}
}
}
var server = http.createServer(function(req, res){
console.log("Request: ", req.httpVersion, req.method, req.url, req.headers);
if( req.httpVersion > 1.1 ) {
res.writeHead(505);
res.end()
} else {
new Routes(req, res).handle();
}
});
server.listen(9000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment