Node JS Server Example

Beginner Node JS Server Example with Routing

What is a Node JS Server?

Node JS gives the front-end developer (and back-end developers) the ability to use JavaScript (JS) as the back-end server-side scripting language instead of other back-end server-side languages. This is exceptionally useful for front-end JS developers looking to do server-side scripting as well. When you develop an application using Node, the application you write is the server. Node is a framework for you to build a web server. To setup and configure Node and NPM, see my tutorial.

beginner node js server
In the following Node JS Server tutorial, I will show you how to create a simple Node JS Server for serving static files using Routing. Routing tells our Node JS server which files (web-pages) to send the user based on the URL request, submitted by the user, through their web browser (Chrome, Firefox, Safari, etc.).

Our Node JS Server will serve a simple index.html file with a logo, and a 404.html file when the user requests a page that does not exist. It is simple to follow and gives you an idea of how NodeJS Servers work.

Node JS Server Tutorial

To create a node js server, First, create a file named nodeServer.js in your project directory (e.g. c:\NodeProjects\nodeServer.js). Open nodeServer.js and in you favorite text editor, type:


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

http.createServer(function(req,res){
    var path = req.url.toLowerCase();  //makes the URL lowercase and saves it to path variable
    switch(path) {  //switch statement for path variable
        case '/':    //serve homepage
            serveStaticFile(res, '/public/index.html', 'text/html');  
            break;
        case '/images/logo.png':  //serve logo
            serveStaticFile(res, '/public/images/logo.png', 'image/png');
            break;
        default:  //default case is set to serve 404 error page
            serveStaticFile(res, '/public/404.html', 'text/html');
            break;
}
}).listen(3000);

console.log('Node Server running on localhost:3000');

The above code uses the http.createServer method that takes a function (function(req,res)) that will be invoked every time a request is made through the users browser. The request (req) which is what the user is asking from via the browser (URL) will be saved to the path variable and converted to lower case (you don’t necessarily have to make everything lowercase, so it is okay to leave it out.) We then use the Switch statement to tell our Node JS Server what to do depending on the value of the path variable.

Finally, in the terminal, or Windows command prompt, type node nodeServer.js and you should get the following:

Node JS Server Tutorial

Our Node JS Server should be up and running, however if you visit http://localhost:3000, the Node JS Server will crash and you will receive the following error in the terminal:

Node JS Server Tutorial

This is because we called the serveStaticFile function in our nodeServer.js file, but we haven’t created/defined it yet. Our serveStaticFile function will serve the static HTML files which contain the content for the web application user. To create the function, we need to append the following code to our nodeServer.js file:


function serveStaticFile(res, path, contentType, responseCode) {
    if(!responseCode) responseCode=200;
    fs.readFile(__dirname + path, function(err, data) {
        res.writeHead(responseCode, {'Content-Type': contentType});
        res.end(data);
    });
}

The serveStaticFile function uses fs.readfile to read the contents of the specified file if the response code is 200 (meaning everything went smoothly). fs.readfile then uses __dirname + path with a callback function(err,data).

__dirname is the path of your application. If your application is in “http://example.com/myapp/myapp.js”, __dirname will return “http://example.com/myapp/”.

After fs.readfile is done reading the file, it executes the callback function. The callback function returns an error (err) if there is an issue serving the file (error code 500). Otherwise, if the callback function is successful in retrieving the data, it will return the specified file with response code and data.

For more information regarding HTML status codes, please see https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html

This should take care of our Node JS server, but we still need to create our actual content (static HTML pages). I am assuming you can understand HTML so I’m not going to go into details regarding the language. Now, in the /public/ folder, create file index.html and 404.html, and in the images folder place any image and name it logo.png. Here is our complete folder and file structure:

Node JS Server example
file/directory structure

Open the index.html file and copy and paste the following code:


<!DOCTYPE html>
<html>
<head>
	<title>Welcome</title>
</head>
<body>
<h2 align="center">Welcome to my Node Website</h2>
<div style="text-align:center;">
<img src="/images/logo.png" />
</div>

<p style="margin:200px;text-align:center;"> Node JS Server is Awesome </p>

</body>
</html>

Next, open the 404.html file and copy and paste the following code:


<!DOCTYPE html>
<html>
<head>
	<title>Page not Found</title>
</head>
<body>
<h3 align="center">404 error - Page not Found</h3>
<p style="text-align:center;">
Please make sure the URL is typed correctly. </p>
</body>
</html>

If you want to create your own index.html and 404.html page, please feel free to do so. Make sure you put the HTML files in the correct folder (/public/).

That is it for our static HTML pages, Here is the complete code to the nodeServer.js file in case you still need it:

Complete Node JS Server

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

function serveStaticFile(res, path, contentType, responseCode) {
    if(!responseCode) responseCode=200;
    fs.readFile(__dirname + path, function(err, data) {
        res.writeHead(responseCode, {'Content-Type': contentType});
        res.end(data);
    });
}

http.createServer(function(req,res){
    var path = req.url.toLowerCase();
    switch(path) {
        case '/':
            serveStaticFile(res, '/public/index.html', 'text/html');
            break;
        case '/images/logo.png':
            serveStaticFile(res, '/public/images/logo.png', 'image/png');
            break;
        default:
            serveStaticFile(res, '/public/404.html', 'text/html');
            break;
}
}).listen(3000);

console.log('Node Server running on localhost:3000');

Finally, run your node server by launching Linux Terminal, or Windows Command Prompt and typing:

node nodeServer.js

To visit our website, open your favorite browser and navigate to http://localhost:3000/. If everything was done correctly, you should see our index.html page. This is case ‘/’ from our Node JS Server JavaScript file.

Node JS Server example
index.html page

If you try to navigate to a page that does not exist, such as http://localhost:3000/about.html, you will be directed (or routed) to our 404.html page.

Node JS Server example
404.html page

Summary

While this a great Node JS Server example, as you can see it can get complicated (and tedious at times) quickly with code and file structure as your application grows. The benefit of Node is the vast amount of packages available for it. Read my Node JS setup guide here.

One great package that takes care of most of the tedious infrastructure work, is called Express. Express sets up your file structure and you can modify the files to fit your needs. To learn more about Express, visit https://expressjs.com/. I might do an Express tutorial in the future so please sign up for your newsletter so you can get updates.

Leave a Reply

Your email address will not be published. Required fields are marked *