node.js http url routing using url.pathname

Objective: Without using any url routing framework, create a node js http server accepting http requests and redirect requests to various functions based on the url path from the request.
Solution: Include the node js native http and url module, use the http to create the http server, and use the url module to get the pathname from the request object, then redirect the request to appropriate places to processed the data.

//include the http and url module
var http = require('http'),
	url = require('url');

//create the http server accepting requests to port 3333
http.createServer(function (req, res) {
	//get url infomation
	var urlParts = url.parse(req.url);
	console.log(req.url, urlParts);

	//direct the request to appropriate function to be processed based on the url pathname
	switch(urlParts.pathname) {
		case "/":
			homepage(req, res);
		case "/read":
			read(req, res);
		case "/svc/update":
			update(req, res);
console.log("Server running at http://localhost:3333/");

//functions to process incoming requests
function homepage(req, res) {
	res.end("Hello, this is the home page :)");	

function read(req, res) {
	res.end("Hello, there is no data for reading yet.");	

function update(req, res) {
	res.end("Hello, there is no data to update.");	

Search within Codexpedia

Custom Search

Search the entire web

Custom Search