MEAN web development #2: Node.js in the back

A series on MEAN and the first actual article in which we’ll get some web pages served starts with the N, the very last letter of MEAN! Yes, it’s true, we’re starting in the back, literally and figuratively speaking. Node.js will be your server side software and you’ll use it to handle incoming HTTP requests. Once we’ve got this going we’ll be able to get to the other letters of MEAN (MongoDB, Express and AngularJS in case you forgot). And in fact we’ll already be looking at some of that E, for Express, in this post!

For a change I won’t mention you should follow me on Twitter because that’s where I tweet on anything software, MEAN and Node.js related and I won’t mention my Twitter handle is @sanderrossel either.
So now that I haven’t mentioned that I am going to mention my GitHub account because that’s where you’ll find the source code for this blog post. You can find the repository for this post in the SanderRossel/mean2-blog repository.

By the way, if you’re just dropping in and you haven’t read the first post in this series yet you really should.

  1. MEAN web development #1: MEAN, the what and why
  2. MEAN web development #2: Node.js in the back
  3. MEAN web development #3: More Node.js
  4. MEAN web development #4: All aboard the Node.js Express!
  5. MEAN web development #5: Jade and Express
  6. MEAN web development #6: AngularJS in the front
  7. MEAN web development #7: MongoDB and Mongoose
  8. MEAN web development #8: Sockets will rock your socks!
  9. MEAN web development #9: Some last remarks

Getting started

Maybe the title of this post seems familiar? I’ve written on a back-end technology before, Web development #4: PHP in the back. In that blog post I explain how to write PHP and how to get it working on your own machine by installing some web server software, XAMPP. Here’s the cool thing about Node.js. It is a web server already, so you don’t need to install anything besides Node.js (which we did in the first part of this series). You can just write JavaScript and run your server!

So let’s look at the “Hello world” example from the first article again.

var http = require('http');
var server = http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello, Node.js!');
});
server.listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');

I’ve written it a bit different from my first post, so we can see what’s going on just a little bit better. There are a few things going on there. First of all is the ‘require‘ bit. With require we can load a module which we can use to implement certain functionality. So what’s a module? Node.js has a pretty cool module system, where a module can be compared to classes like we have in C# or Java. We’ll look at modules in more detail in a next post. So anyway, with the first line of code we’re telling Node.js that we need the http module and we store it in the http variable.

So now that we have this http module, or class-like thing, we can invoke functions on it. And the first (and only) function we’re going to call is createServer. So createServer takes an (optional) callback function as parameter. The callback function takes a request and a response as input parameters which we can use to see what the user requested and to return anything back to the client.
As you can see we’re writing to the header of the response, using writeHead, to tell it that everything was handled correctly (HTTP code 200 is OK) and that we’re sending back some plain text. By calling response.end we’re telling Node.js we’re done and that the result is ready. Response.end must be called on each request (or our client will be waiting on a response forever) and it must be called as the final operation on our response object, since it signals that the response is complete (all headers and content have been written to the response). In this case we’re passing our response text directly to the end function, but alternatively we could use the write function and simply call end without parameters. That would look as follows.

res.writeHead(200, {'Content-Type': 'text/plain'});
res.write('Hello, Node.js!');
res.end();

Or, if you want to build up some response text, you can do something as follows (using write n times).

res.writeHead(200, {'Content-Type': 'text/plain'});
res.write('Hello,');
res.write(' Node.js!');
res.end(' [This text is optional]');

And, of course, we’ll typically return HTML rather than plain text. Notice I’ve changed the header too.

res.writeHead(200, {'Content-Type': 'text/html'});
res.end('<h1>Hello, Node.js!</h1><p>This is a paragraph...</p>');

So now that we’ve called the createServer function and we’ve specified what to return we have a Server object. This Server object has functionality to listen for incoming HTTP requests and handle them accordingly. To start listening simply call the listen function and pass it a port and an IP address. I’m still using 1337 and localhost from the Node.js website example.

Last, and actually also least, is the console.log, which just logs some debug info to your command window when starting your Node.js app.

You can run each example by opening up a command prompt and typing in (exluding double quotes (“”)) “node pathToMyFile\MyFile.js”. If your file path contains any spaces be sure to wrap it in double quotes.

Debugging

Did you try out all those examples? Did you have to restart the command prompt and type in “node pathToMyFile\MyFile.js” a couple of times? Tiresome, isn’t it? Luckily there are tools that automatically restart your Node.js app when changing a file. You really should install one and save yourself time and trouble! I’m going to use nodemon. You can install it using npm. Open up a command window and type “npm install nodemon -g”. The -g tells npm to install nodemon globally. That means nodemon isn’t some library that this one project uses, it’s a global library from which all your projects can benefit! Whoohoo, never again restart your Node.js app manually because you’ve made a minor file change! To make sure nodemon installed correctly open up a command prompt and type in “nodemon -v” and you should get the currently installed version of nodemon.
Now instead of starting your Node.js app using “node pathToMyFile\MyFile.js” use “nodemon pathToMyFile\MyFile.js” (simply replace node with nodemon). Now go ahead and edit your file. Watch the command prompt and see how your app is automatically restarted. Browse to your website (localhost:1337) and see that the Node.js app has indeed restarted.

For some more tips on debugging web apps in general (no matter if you’re using Node.js, C# ASP.NET, Java or what have you) you should read a previous blog post I wrote, which has a little section on debugging web pages from your browser, Web development #8: Where to go from here.

Doing a little more

So here’s a nice one for you.

res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Requested: ' + req.method + ' - ' + req.url);

Try putting that in the createServer callback. Now browse to localhost:1337/SomePage or localhost:1337/AnotherPage?someParam=someValue. You should see whatever you put after localhost:1337 echoed in your browser window.

So let’s say we have some HTML pages that we want to show based on the requested page. This is now pretty easy. Here’s a first, and rather naive, implementation. In case you got my source from GitHub, the final implementation can be found in the file nope.js (that kind of gives away the ending, doesn’t it?).

var http = require('http');
var fs = require('fs');

var server = http.createServer(function (req, res) {
    switch (req.url) {
        case '/about.html':
            res.writeHead(200, {'Content-Type': 'text/html'});
            var buffer = fs.readFileSync(__dirname + '\\about.html');
            res.end(buffer.toString());
            break;
        case '/index.html':
        case '/':
            res.writeHead(200, {'Content-Type': 'text/html'});
            var buffer = fs.readFileSync(__dirname + '\\index.html');
            res.end(buffer.toString());
            break;
        default:
            res.writeHead(404, {'Content-Type': 'text/html'});
            res.end('<h1>404 - Page not found!</h1><p>What were you even trying to do...?</p>');
            break;
    }
});
server.listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');

So there’s some new stuff in there. First we require(‘fs’), which gives us some control over the file system (fs is short for File System). After that we do a switch statement on the request url. We support no url (just localhost/1337, we’ll get url “/”), /index.html and about.html. Everything else will get a 404, page not found. Note that no url and index.html both give you the index.html page. So make sure you have an index.html and an about.html page in the same folder as your Node.js app. If you got this from my GitHub account you’ll be fine, otherwise you’ll need to create those files and put some HTML in them.
So if you browse to localhost:1337/index.html or about.html we’ll first set the header to 200 and text/html. After that we’ll use the fs object to read either the index.html or the about.html file.
Notice that I’m using readFileSync. Remember that I explained, in my first post in the series, that Node.js runs a single thread to handle all incoming requests? Because any synchronous action (meaning it just runs on the same thread) is blocking that one thread everything in Node.js is asynchronous by default. So any non-asynchronous (synchronous) method is suffixed with ‘Sync’. If, like me, you’re coming from C# that’s just the other way around from what you’re used to!
So anyway, we read the file and we now get some buffer object. To get the actual contents as a string simply call the toString function on the buffer.
We also see the __dirName variable, which is a global Node.js variable which contains the directory in which your Node.js JavaScript file resides.

There is an overload for the readFileSync that will return the string value instead of the Buffer object.

var content = fs.readFileSync(__dirname + '\\index.html', 'utf8');
res.end(content);

So there are a few problems with this code. First of all we are reading files synchronously. Suppose this takes 50 milliseconds. No big deal you’d say, but suppose you have 100 requests per second, that’s 5000 milliseconds, or 5 seconds, for the 100th visitor! Imagine that every 100th visitor had to wait 5 seconds, at least, for your page to load. That’s rather disastrous for a web page! So we really want to read that file asynchronous. Luckily that’s pretty easy. We can use the readFile function which takes a callback function as last parameter. The callback function gets an error object and the returned data as input parameters. So how would that look?

fs.readFile(__dirname + '\\index.html', 'utf8',
    function (err, data) {
        if (err) {
            // Handle exception...
        } else {
            res.writeHead(200, {'Content-Type': 'text/html'});
            res.end(data);
        }
});

Second, we’d best put the file handling in a seperate function. We now have this ‘huge’ piece of duplicated code! So let’s tidy it up a bit.

var http = require('http');
var fs = require('fs');

var readHtml = function (fileName, res) {
    fs.readFile(__dirname + '\\' + fileName, 'utf8',
        function (err, data) {
            if (err) {
                // Handle exception...
            } else {
                res.writeHead(200, {'Content-Type': 'text/html'});
                res.end(data);
            }
    });
};

var server = http.createServer(function (req, res) {
    switch (req.url) {
        case '/about.html':
            readHtml('about.html', res);
            break;
        case '/index.html':
        case '/':
            readHtml('index.html', res);
            break;
        default:
            res.writeHead(404, {'Content-Type': 'text/html'});
            res.end('<h1>404 - Page not found!</h1><p>What were you even trying to do...?</p>');
            break;
    }
});
server.listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');

So, all fixed, right? Well, actually, this looks more like Nope.js! Well alright, I suppose it’s not that bad, but once your app starts to get bigger this approach might get a little messy. Let’s add some Express and see how it can help make things easier.

Just a little remark on the 404 HTML. Of course it would be better to create another HTML file for the 404 page, but I just wanted to show you that you can use multiple methods of returning HTML even if you’ve already used another method.

Adding some Express

In the first part of this series we’ve installed Express in our project, so I’m assuming you’ve got it set up. As said Express just makes working with Node.js a lot easier. It handles routing, rendering of HTML, sessions, template engines and all that stuff. So let’s rewrite the above code so it uses Express.

var express = require('express');
var app = express();

var options = {
    root: __dirname
}

app.get(['/', '/index.html'], function (req, res) {
    res.sendFile('index.html', options);
});
app.get('/about.html', function (req, res) {
    res.sendFile('about.html', options);
});
app.get('*', function (req, res) {
    res.send('<h1>404 - Page not found!</h1><p>What were you even trying to do...?</p>'); 
});

var server = app.listen(1337, '127.0.0.1');

First we’re requiring Express. This actually doesn’t return an object, but a function, also called the express function, and as you can see on the second line we just run the function and store the result in our app variable. This app variable now denotes our Express application. After that we use the app.get function multiple times to handle our routing. I think it’s pretty straightforward. If “/” or “/index” are requested we return the index.html file, if “/about” is requested we return the about.html file and if anything else is requested we send back the 404 HTML.
It’s worth mentioning that the send and sendFile functions set the header of the response object. sendFile sets the header based on the file extension (in these cases .html) and you can override it in the options object. We only use the options object to set the root of the files though, in our case that’s the same folder as our app resides in, but for bigger projects it would be wise to create a /views folder or something like that.
Finally we call app.listen and pass in our port and IP address. Notice I’ve used the same port and IP as the nope.js example, so you can’t run them both simultaneously.

Here’s another thing Express handles pretty well. Parameters and queries. Using the request object we can ask for any parameter or query that the user sent our way. Here a little example.

app.get('/echo.html', function (req, res) {
    res.send('<h1>Echo</h1><p>This is an echo... ' + req.query.say + '</p>');
});

Using the query object we can get the value of any query parameter. In this case we expect a parameter called “say” and its value will be echoed to your browser. So just browse to localhost:1337/echo.html?say=someValue.
Pretty neat, right?

There are some other best practices, like putting your routing in a separate file and exception handling, that we haven’t discussed yet. No problem, since we’ve only scratched the surface anyway. Don’t worry, we’ll go in a little deeper yet in my next post!

And as always I’d like to give you some reading recommendations. Syncfusion has an awesome free ebook on Node.js, Node.js Succinctly. Just sign up and get them free Succinctly books! They have lots more, like JavaScript Succinctly and HTTP Succinctly, which might come in handy when working with Node.js.
And it also just so happens that Manning Publications has quite a few books on the MEAN stack as well! They’re not free, but when you really want to do some Node.js heavy lifting I can really recommend getting one of them. So they’re Node.js in Action, Node.js in Practice and Express.js in Action.
And, of course, you could also just keep following my blog, which is free and a lot less to read.

Stay tuned!

7 thoughts on “MEAN web development #2: Node.js in the back”

  1. I’m enjoying this series. Please keep up the good work.

    I’m new to web development also – a recurring theme that comes up in my work is authentication and access control. I’m finding it confusing. Do you have any experience you can share on this topic?

    1. Thanks! I’m glad you like it!
      I was planning to write a bit about authentication and security.
      Not sure when that’s going to happen though, as I’ve got lots of topics to write about.
      Perhaps I can fit it into this MEAN series… I’ll see what I can do!

  2. Sander,
    Awesome series, I’ve been wanting to get into either Node.js or SignalR for some time and for the past couple of days been pouring over tutorials and I’m glad I ran into yours on CP which led me here.
    Great job man!

    Mike

    1. Hi Mike,
      Thanks!
      Awesome to hear my tutorials helped you out 🙂
      As it happens I’ve got a guest blog on another website on SignalR coming out somewhere next month. Too bad it’s in Dutch, so it won’t help you much… Anyway, SignalR is pretty neat and quite easy to start with. So I can really recommend trying it out sometime.

      See you on CP,
      Sander

Leave a Reply