This site uses 3rd-party cookies for targeted advertising. If you do not agree to this, then please leave this site now. Otherwise please click on "Ok" to continue.
Ok
 
 

Why is this function here?

07-Jan-2015

Today let's take another look at blogforum.js.

At the end of course is the initialization-code. Above that is the RequestListener() callback which checks what the user wants to see, and then sends the request further down the line. And we have handleBlog() and handleBlogIndex().

First thing we notice is that handleBlogIndex() does a lot of stuff which is not just routing further processing, but which is actual processing. Well, that doesn't belong in this file. It's on a different level of abstraction. So let's move it to its own file handle-blog-index.js.

Some Copy/Paste later...

Checking the require() statements, it is clear that path and te are no longer needed in blogforum.js.

Ok, now let's see how the function for handleBlogIndex() that we just moved looks like:

"use strict";

var tools = require('./tools.js');
var config = require('./config.js');
var path = require('path');
var te = require('./template-engine.js');





module.exports =
function( req, res, hostname, indexFilename, postFilename, resType ) {

    var startTime = new Date();
    var templatesDir = config[hostname].templatesDirectory;
    var blogDir = config[hostname].blogDirectory;


    var indexTemplate = tools.loadFile(
	path.join( templatesDir, indexFilename ),
	'Unable to load template "' + indexFilename + '"'
    );

    var postTemplate = tools.loadFile(
	path.join( templatesDir, postFilename ),
	'Unable to load template "' + postFilename + '"'
    );





    // Read index.txt
    var index = tools.loadFile(	path.join(blogDir, 'index.txt') );
    if ( index === '' )
	indexTemplate = 'Unable to load blog-index.';

    var indexLines = index.toLines();




    // For every item in index.txt load the blog-entry
    // Then process the entry according to blogindexpost.html template
    var blogPosts = ''; // This will hold all the combined blog-posts

    for (var i=0; i<indexLines.length; i++) {
	if (indexLines[i].length>0) {
	    // Split entry into Url and filename
	    var j = indexLines[i].search( ' ' );
	    if (j) {
		var url = indexLines[i].substr( 0, j );
		var filename =
		    indexLines[i].substr( j+1, indexLines[i].length-j );

		// Load raw blog-entry
		var s =
		    tools.loadFile( path.join(blogDir, filename + '.html') );

		// If the file could be loaded, process it using the template,
		// and add the result to the combined blog-posts.
		if (s !== '') {
		    var dataItems = te.parseSource( s );
		    dataItems['url'] = config[hostname].baseUrl + url;
		    dataItems['id'] = filename;
		    blogPosts += te.processTemplate( postTemplate, dataItems );
		}
	    }
	}
    }



    // Integrate all the combined blog-posts into blogindex.html template
    var dataItems = te.parseSource( blogPosts );
    var index = te.processTemplate( indexTemplate, dataItems );


    res.writeHead(200, "OK", {'Content-Type': resType});
    res.end( index );

    var endTime = new Date();
    console.log( 'Built blog-index in ' + (endTime - startTime) + 'ms' );
};

Uh... that's a bit long for one function. About 70 lines. Better split that up. The big for-loop which reads all the blog-posts and combines them into one piece looks like a good candidate. So let's move that into its own function together with some stuff associated with the loop.

And while we're at it, let's remove the (debug-) code which measures how long handleBlogIndex() takes. That was only good during development and should have been removed a long time ago.

That leaves us with this code for handleBlogIndex():

module.exports =
function( req, res, hostname, indexFilename, postFilename, resType ) {

    var templatesDir = config[hostname].templatesDirectory;
    var blogDir = config[hostname].blogDirectory;


    var indexTemplate = tools.loadFile(
	path.join( templatesDir, indexFilename ),
	'Unable to load template "' + indexFilename + '"'
    );


    var blogPosts =
	getAllBlogPosts( hostname, blogDir, templatesDir, postFilename );


    // Integrate all the combined blog-posts into blogindex.html template
    var dataItems = te.parseSource( blogPosts );
    var index = te.processTemplate( indexTemplate, dataItems );


    res.writeHead(200, "OK", {'Content-Type': resType});
    res.end( index );
};

Yes, this looks good. Short and clear. And what about our new function getAllBlogPosts() ?

function getAllBlogPosts( hostname, blogDir, templatesDir, postFilename) {

    var postTemplate = tools.loadFile(
	path.join( templatesDir, postFilename ),
	'Unable to load template "' + postFilename + '"'
    );


    // Read index.txt
    var index = tools.loadFile(	path.join(blogDir, 'index.txt') );
    if ( index === '' )
	indexTemplate = 'Unable to load blog-index.';

    var indexLines = index.toLines();




    // For every item in index.txt load the blog-entry
    // Then process the entry according to blogindexpost.html template
    var blogPosts = ''; // This will hold all the combined blog-posts

    for (var i=0; i<indexLines.length; i++) {
	if (indexLines[i].length>0) {
	    // Split entry into Url and filename
	    var j = indexLines[i].search( ' ' );
	    if (j) {
		var url = indexLines[i].substr( 0, j );
		var filename =
		    indexLines[i].substr( j+1, indexLines[i].length-j );

		// Load raw blog-entry
		var s =
		    tools.loadFile( path.join(blogDir, filename + '.html') );

		// If the file could be loaded, process it using the template,
		// and add the result to the combined blog-posts.
		if (s !== '') {
		    var dataItems = te.parseSource( s );
		    dataItems['url'] = config[hostname].baseUrl + url;
		    dataItems['id'] = filename;
		    blogPosts += te.processTemplate( postTemplate, dataItems );
		}
	    }
	}
    }

    return blogPosts;
}

Ok, now that is still too long. With all the stuff outside the actual for-loop, which we moved as well, this is still too long. Let's see how this looks if we move everything which is inside the for-loop into yet another function. This leaves us with this for getAllBlogPosts():

function getAllBlogPosts( hostname, blogDir, templatesDir, postFilename ) {

    var postTemplate = tools.loadFile(
	path.join( templatesDir, postFilename ),
	'Unable to load template "' + postFilename + '"'
    );


    // Read index.txt
    var index = tools.loadFile(	path.join(blogDir, 'index.txt') );
    if ( index === '' )
	indexTemplate = 'Unable to load blog-index.';

    var indexLines = index.toLines();



    // Process every item in index.txt and combine all the posts
    var blogPosts = ''; // This will hold all the combined blog-posts

    for (var i=0; i<indexLines.length; i++) {
	blogPosts +=
	    getSingleBlogPost( hostname, indexLines[i], postTemplate, blogDir );
    }

    return blogPosts;
}

And with this for our new getSingleBlogPost():

function getSingleBlogPost( hostname, indexLine, template, blogDir ) {
    if (indexLine.length>0) {
	// Split entry into Url and filename
	var j = indexLine.search( ' ' );
	if (j) {
	    var url = indexLine.substr( 0, j );
	    var filename =
		indexLine.substr( j+1, indexLine.length-j );

	    // Load raw blog-entry
	    var s = tools.loadFile( path.join(blogDir, filename + '.html') );

	    // If the file could be loaded, process it using the template
	    if (s !== '') {
		var dataItems = te.parseSource( s );
		dataItems['url'] = config[hostname].baseUrl + url;
		dataItems['id'] = filename;
		return te.processTemplate( template, dataItems );
	    } else return '';
	}
    } else return '';
}

This looks good. And after some manual testing, we see that it still works. :)

If you want to take a look at the full source-code as it was at the end of this blogpost, you can get it from GitHub:

git clone https://github.com/MichaelSchoebel/blogforum
cd blogforum
git checkout blog-2015-01-07

That's enough for today... See you soon...

Comments:

You want to comment on this blog-post? If yes, then simply enter your comment in the field below and click on "Submit".

Comments are moderated at the moment thanks to some $%&# who thought it would be funny to post total nonsense here.

 


Back to the Homepage

A Programmer's Diary