friendlyTracker – my test project in Node and Express

I finally did it – I started my first real project in Node using Express. I want to implement web application without digging too deep in Node from the day 1. The idea is rather simple – I want to collect (and display somehow) my numeric statistics. Most likely I will add more features in the future, but I want to start from this particular functionality. I know that there are already apps doing the same, but I want to do it my way just to make sure that I will have control over all aspects of the implementation and behavior of the application. Let’s start.

Express application generator

I used Express.js application generator to generate my application skeleton. I used Handlebars as the view manager (view layer) and skipped CSS engine for now (I don’t want to learn CSS frameworks today). Once generated and “installed” using npm I was able to start my new app and open it in my browser. That was fast and that was what I expected – the running piece of code which can be expanded the way I want. I took a look at the directory structure and I found some useful information just by looking at the code of the particular files.

What’s in there…

Starting with /bin/www file – this is the main file of the application as far as I can tell. This one creates the WWW server on the port defined in settings (default: 3000), handles listener errors and calls app itself.

app.js which is located in the root directory of the project handles dependencies such as Express itself and modules such as serve-favicon or cookie-parser. I also found basic routing settings here and added my own – just for test. I added routes to /users/ URL and /siteAdmin/ URL because I expect that there will be some kind of the user area – available for logged in users, and some kind of the admin area.  At the end of the file, there are also two error handlers – one for 404 Page Not Found errors and one general which should be called in all cases other than 404 error.

Directory public contains static files that should be served by the application but should not trigger any business logic related actions. At the beginning, there is only stylesheets directory in there with the single style.css file.

Directory routes contain js files which should handle particular routes in my application. Once I added my new routes to the app.js file, I also created proper js files here to handle new routes.

Directory views is filled with Handlebars template files. These files are used when you are creating the response to the user request – you can simply render the response using the template and set of variables provided by your application logic.

At first, it was looking pretty straight-forward for me. I played a little with the files and functions inside them to check my assumptions and I was glad that everything is working fine and as I expected.

Why I have to stop and start my application over and over again?

I noticed that after each change made in the code, I have to stop current application instance and start a new one. This is caused by the fact that files are loaded during the application start and they are stored in memory. Node is not checking for changes on its own.

This issue was rather easy to fix. I found that there is utility named nodemon which is able to monitor your files and reload the application on every change. Now, instead of using npm start to execute my application I’m using nodemon ./bin/www which is working exactly the same but takes care of file changes. Handy.

Can I break it?

I wanted to check if I can break my application easily. This is not good if the simple error in your code is breaking the whole thing. I started by creating the faulty function and I used it as the route handler for /siteAdmin/thisIsNotWorking URL. As I expected, errors are handled by Express. There is even stack trace displayed to inform you where given error occurred. This is good enough for now, but I will also look for more detailed debugging possibilities.

On Request End, On Request Start

I’m using ColdFusion for more than ten years now. This means that I’m familiar with some concepts and I want to use them in my node application now. One of such things I find handy is On Request Start and On Request End code execution. Such function gives me an ability to check (execute) something at the beginning and end of each request. In some cases, I’m using it to perform security-related tasks. In other – to perform application-level logging. It can be also handy to gather application performance information. I guess that you will find your ideas how to use them.

Fortunately, there is an easy way to handle On Request Start and End actions also in Express based application. To catch request start, I created the function and used it as the first in the long list of app.use executions in app.js file. The app.use can be called with the route you want to apply your code to, but I wanted to call it on each request, so my code is looking as follows:

app.use(function(req,res,next) {
    console.log('on Request Start');
    next();
})

Request End is a little bit more tricky. You still have to place this handler at the beginning of your app.use executions, but there is listener added to the response object:

app.use(function (req, res, next) {
    function afterResponse() {
        res.removeListener('finish', afterResponse);
        res.removeListener('close', afterResponse);

        console.log('on Request End');
    }

    res.on('finish', afterResponse);
    res.on('close', afterResponse);

    next();
});

As you can see, in both cases there is next() called at the end of the function. This is because we don’t want to stop application execution in this particular function. We want it to follow the whole execution chain.

Conclusion for today

I think that I started to feel how Node and Express are working together to deliver the response to the client’s request. I also found answers to the few questions I had and I’m making a list of other things to check. For now, the list is getting bigger and bigger but hopefully, during the implementation process, I will find answers to all my questions. I will do my best.

My FriendlyTracker application code is available on GitHub if you are interested.