Skip to content

Instantly share code, notes, and snippets.

@leommoore
Last active October 4, 2015 10:28
Show Gist options
  • Select an option

  • Save leommoore/2621016 to your computer and use it in GitHub Desktop.

Select an option

Save leommoore/2621016 to your computer and use it in GitHub Desktop.
Node - Basic Web Service

##Node - Basic Web Service

var util = require('util'),
http = require('http');

/*
/add/2/2 => 4
/sub/103/42 => 61
/mul/3/2 => 6
/div/100/25 => 4
*/

var operations = {
  add: function(a,b){return a + b},
sub: function(a,b){return a - b},
mul: function(a,b){return a * b},
div: function(a,b){return a / b}
}

http.createServer(function(req, res){
var parts = req.url.split("/"),
    op = operations[parts[1]],
    a = parseInt(parts[2],10),
    b = parseInt(parts[3],10);
    
var result = op ? op(a,b) : "Error";

util.puts(util.inspect(parts));
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end("" + result);
}).listen(3000, "127.0.0.1");

util.puts("Server running at http://127.0.0.1:3000/")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment