How to use Nodejs - For Absolute Beginners (Part 2)

How to use Nodejs - For Absolute Beginners (Part 2)

Making a Server

Making a sever in nodejs is pretty easy. Node comes with an in-built module called http that we can use to make a server. We can access the http module as below var http = require('http');

Armed with the http module, we can go ahead and now create our server.

 http.createServer(function (req, res) {
        res.writeHead(200, {'Content-Type': 'text/plain'});
        res.write('Hello World!');
        res.end();
 }).listen(3000);
 console.log("We are now listening on port 3000"); // helps us know our app is actually running

line 1: http.createServer(function (req, res) { - this pretty much explains itself. We create a server with it. The function we pass to the createServer method is how we define what we want our server to do when the app is called. The req contains request information while res is used to handle the response our server will make upon being called.

line 2: res.writeHead(200, {'Content-Type': 'text/plain'}); - if you are familiar with http status codes, you would realize that status 200 means ok. So, we are sending a status 200 to the browser to tell it everything is fine. We are also sending another header along with it, to help the browser know how to render the data it is receiving - '``Content-Type``'``: '``text/plain``'. Pay attention to the letter casing as it matters when sending headers.

line 3: res.write(``'``Hello World!``'``) - This simply writes data to the browser.

line 4: res.end() - this tells node “We are done sending stuff to the browser, so you can render now”. If you are curious like me, remove this line and reload your app (use ctrl + c to stop the app then run node app again to start it). Then refresh your browser and see what happens.

line 5: }).listen(3000); - this is where we serve our app via localhost on port 3000.

Super cool right?

Serving Data to the web browser

In this part of this tutorial, we will learn how to serve html pages as well as how to return json data (you know json data is very important when making APIs). Node serves pages just like other regular server side scripts. You could either have your page as plan HTML or make it dynamic using templating engines like EJS (we will learn about it as we progress). You would not notice much difference between node and server side scripts, except you’d be seeing .js everywhere which can look weird sometimes. That makes this seem like rocket science but you’d get used to it in no time at all.

By the time we are done, we should have a basic working knowledge of how to return data when a call is made to our app. Shall we begin?

Return JSON string

Returning JSON is important especially when we are creating APIs for our app. We also use JSON when we need to send data to our app to make updates or changes. JSON is a really effective way to send data as you can have multiple data items inside a single JSON object. In es6, Javascript has provided a lot of methods for manipulating JSON data making it even easier to use.

Below, we have a simple code to return JSON data to our web browser.

var http = require('http');
var jsonData = {
        'name': 'NodeJS',
        'lang': 'Javascript',
        'use': 'Write once, run everywhere'
};
http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'application/json'});
    res.end(JSON.stringify(jsonData));
}).listen(8080);
console.log("We are now listening on port 8080"); //Helps us know our app is actually running

So, we have created our JSON data and already presented it by changing our 'Content-Type': to 'application/json'. We can run it in the browser now to see the outcome.

If we run it in the browser, this is what we get.

Return HTML

What would our app be if we do not return HTML? Is that not the entire purpose of this journey we have been on? Quickly create a file named index.html and define any HTML markup you like. Here is what I did in mine.

<html>
        <head>
                <title>Learn Routing - NodeJS</title>
        </head>
        <style type="text/css">
                body{
                        margin:0 auto;
                        width: 50%;
                }
        </style>
        <body>
                <h1>We are live on the homepage</h1>
                <p>This is some cool stuff. We can get a lot of stuff happening here for the purpose of our learning. Cool right?</p>
        </body>
</html>

Now, let us see how we can easily return our HTML to the browser.

    var http = require('http');
    var fs = require('fs');
    http.createServer(function (req, res) {
        fs.readFile('./index.html', function(err, data) {
        res.writeHead(200, {'Content-Type': 'text/html'});
        res.write(data);
        res.end();
    });
    }).listen(8080);
    console.log("We are now listening on port 8080"); //Helps us know our app is actually running

We have introduced a new bad boy here fs - File System. We use fs to manipulate files (read or write to them however we want). line 4: fs.readFile('./index.html', function(err, data) { - fs has a method called readFile that obviously reads the content of any file you pass to it. In our case, we passed the index.html file to the method and also a function to perform action when fs is done reading the file (such functions are called callbacks). We read the contents of the file into the variable data so we can use it inside our callback.

Here is what it looks like when we run it.

Ok. So we have learnt how to return HTML and JSON to our browser. There is nothing holding us back from really building even cooler stuff with NodeJS though. So far, this has been pretty cool right?

Check out the first part Getting started.

Next up Using NPM, Express, EJS and Basic Routing to build a Node App