«®»
Home About Work Contact Quotes

Handling one-off events with callbacks, Reduced nesting by creating intermediary functions (Node.js)

Prerequisite: JavaScript knowledge, I'd say you need to at least understand the server-client model and how the HTTP protocol works. that should be enough to get you started if you already know JS. Node installation steps can be found here - https://nodejs.org/

This example is based on my last post - Handling one-off events with nested callbacks

We have added functions in js file only.

blog_recent.js

Following code will pull JSON file and render the web page.

//Load http,fs modules to create an http server and read files
var http = require("http");
var fs = require("fs");

//Client request initially comes in here
http.createServer(function (request,response) {
	
	if (request.url!="/") {
		return hadError("Page not found!",response);
	}

	//Control is passed to getTitles
	getTitles(response);
	
}).listen(4000,"127.0.0.1");

//Put a friendly message on the terminal
console.log("Listening to 127.0.0.1:4000");

//getTitles pulls titles and passes control to getTemplate
function getTitles (response) {

	fs.readFile("titles.json",function (error,data) {
	//Instead of creating an else branch, you return,
	//because if an error occurred you don’t need to continue executing this function.
		if (error) 
			return hadError(error,response);
		
		getTemplate(data,response);
	});
}
//getTemplate reads template file and passes control to formatHtml
function getTemplate (data,response) {
	
	var titles = JSON.parse(data.toString());
	fs.readFile("template.html",function (error,data) {
		
		if (error) 
			return hadError(error,response);

		formatHtml(titles,data.toString(),response);
	});
}

//formatHtml takes titles and template, and renders a response back to client
function formatHtml (titles,template,response) {
		var html = template.replace("%",titles.join("</li><li>"));
		response.writeHead(200,{"Content-type":"text-html"});
		response.end(html);
}

//If an error occurs along the way, hadError logs error to console and responds to client with "Server Error"
function hadError (error,response) {
	response.end(error);
}

Now as you have learnt how to use callbacks to handle one-off events, let's move on to organizing events using event emitters