Building Web Application Using Node.js

Introduction

In this article, we will learn how can we develop a web application, using Node.js. Let's start step by step.

First of all, I am going to create one folder for my project. I am giving my project a name as "nodeproject" and initialize the project.

  1. Now, open the Command Prompt.

  2. Go to your project folder. Example - I have created my project in E drive, so I will use the following commands.

    node.js

  3. Now, type "npm init" command to initialize the Node.js project and hit Enter.

    node.js

  4. Now, it will ask some questions. Just press Enter for all the questions.

    node.js

    Note - npm init was not handling errors returned by package name validation correctly in all the cases. New package names cannot contain capital letters, which are documented in few places.

    Well, this problem has been fixed after npm 2.9.0 version.

  5. The command, mentioned above, will generate "package.json" file in your project folder. When you look at this file, you will find the file, mentioned below.
    1. contains all the stuffs like the name of the project, version, description and all. {  
    2.     "name""nodeproject",  
    3.     "version""1.0.0",  
    4.     "description""",  
    5.     "main""index.js",  
    6.     "scripts": {  
    7.         "test""echo \"Error: no test specified\" && exit 1"  
    8.     },  
    9.     "author""",  
    10.     "license""ISC"  
    11. }  
    The primary goal of this package.json file is to keep track of all the dependencies in the packages that we have installed for our application.

Now, let's install Express.

According to http://expressjs.com/, Express is a minimal and flexible Node.js Web Application Framework that provides a robust set of features for web and mobile applications. You can use the steps, mentioned below, to install Express in your project.
  1. In the Command Prompt, just type the command, mentioned below.
    1. npm install express--save  
    node.js

  2. After installing Express, you will get a new folder inside your project i.e node_modules. In this folder, you can get Express folder where you will get the complete package of Express.

    node.js

  3. Now, if you look into your package.json file, you will get the dependency of Express.

    node.js

In package.json, I am changing the name of main JavaScript file to app.js.

  1. {  
  2.     "name""nodeproject",  
  3.     "version""1.0.0",  
  4.     "description""",  
  5.     "main""app.js",  
  6.     "scripts": {  
  7.         "test""echo \"Error: no test specified\" && exit 1"  
  8.     },  
  9.     "author""",  
  10.     "license""ISC",  
  11.     "dependencies": {  
  12.         "express""^4.14.0"  
  13.     }  
  14. }  
Now, I am creating a JavaScript file with the name "app.js" in my project folder and write the code, mentioned below, in this file.
  1. var express = require('express'); //including express   
  2. var app = new express(); // Creating instance   
  3. var port = 3000; // setting port for the application   
  4. //Following function is starts sockets and start listen from particular port. In following code I have given call back which contains err. So when port willbe start and listen function will be fire then this function will be execute.   
  5. app.listen(port, function(err) {  
  6.     if (typeof(err) == "undefined") {  
  7.         console.log('Your application is running on : ' + port + ' port');  
  8.     }  
  9. });  
When you run the code, mentioned above, you will get the following output.

node.js

In your Web Browser, you will get the following output.

node.js

Now, in the next step, I am going to show you how to set the start point of our project.

Now, to run my application, I fired the command "node app.js", where I am telling my application that I want to run the app.js file. Hence, every time I run my project, I have to tell the compiler that this is the file that needs to be compiled. But a project may contain more than one file, so if I give my project to someone, they have to find which file needs to be executed.

Thus, there should be a standard way. That means, we need to type any file name  which is the starting point of the project. To do this, we have to modify our package.json file, as shown below
  1. Declare the start object in Scripts object.
    1. "start""node app.js"  
    node.js

  2. After changing in package.json file, just save the file. Now, you can run your project, using "npm start" command.
    1. npm start  
    After typing this, you will get the output, as shown below.

    node.js

    Here, in the figure, mentioned above, you can see that this command explicitly fires, and "node app.js" is the command when we are giving npm start command. Hence, this is a standard way to run the Node project. Thus, we need not to worry about which file needs to be started in order to execute our project.

Before going further, let's understand how to do routing of the application in Node.js.

How to perform routing in Node.js application?

To understand routing in Node application, consider the code, mentioned below.

  1. app.get('/'function(req, res) {  
  2.     res.send('<h1>Hello C# Corner.</h1>');  
  3. });  
  4. app.get('/articles'function(req, res) {  
  5.     res.send('<h1>Welcome to C# Corner Articles.</h1>');  
  6. });  
Here, I have created two routes. The first one is defined by "/" which means when request comes to the main page, one function will be fired. So, you can see both apps contain a call back function that contains two parameters, where req means Request and res means Response. Hence, when requested for main page, then for response "<h1>Hello C# Corner.</h1>" will be returned and when request will be on /articlespage, then response will be "<h1>Welcome to C# Corner Articles.</h1>".

You can see my complete code below.
  1. var express = require('express');  
  2. var app = new express();  
  3. var port = 3000;  
  4. app.listen(port, function(err) {  
  5.     if (typeof(err) == "undefined") {  
  6.         console.log('Your application is running on : ' + port + ' port');  
  7.     }  
  8. });  
  9. app.get('/'function(req, res) {  
  10.     res.send('<h1>Hello C# Corner.</h1>');  
  11. });  
  12. app.get('/articles'function(req, res) {  
  13.     res.send('<h1>Welcome to C# Corner Articles.</h1>');  
  14. });  
  15. When you will run this code then you will get following output.  
node.js

Note - To run this project, always use npm start.

In the example, mentioned above, you can see when I am requesting for localhost:3000, I am getting 'what'; and when I am requesting localhost:3000/articles, I am getting 'what'.

Now, after understanding about routing, I am going to download a template and use it my project. Thus, let's understand how we can add templates in our project.

Adding Template in Project
  1. Download any template from any website. I have downloaded the template from the link(Click here to download template) .
  2. My template folder structure is shown below.

    node.js

  3. Now, I am creating 2 folders in my project, where folder names are "public" and "src". In public folder, I will keep CSS files, JavaScript files, and Fonts. On the other hand, in src folder, I am creating one more folder i.e. "views". In views folder, I will keep my HTML files. My project folder structure is shown below.

    node.js

  4. Now, from the template, I am copying CSS, JavaScript, and Font file in "public" folder, and HTML files inside "src >> views".

    After copying these files to the folder, my folder structure looks, as shown below.

    node.js

  5. Now, after adding the template, as we know, we have moved our all static files to public, we need to set static file path, so CSS, JavaScript and font file will be loaded from public folder.

    To set the path for static files, we have to modify our app.js file. To set the public directory as static directory, we need to write the code, mentioned below, in our app.js file.
    1. app.use(express.static('public')); //making public directory as static diectory  
    The line, mentioned above, will make public directory as static directory. So, whenever a request occurs for any static file, the Node.js file first searches in public directory, then in other folders, if the file is not found.

  6. To verify my code, we can run the code and can request any CSS or JavaScript file.

    node.js

    Complete app.js code
    1. var express = require('express');  
    2. var app = new express();  
    3. var port = 3000;  
    4. app.listen(port, function(err) {  
    5.     if (typeof(err) == "undefined") {  
    6.         console.log('Your application is running on : ' + port + ' port');  
    7.     }  
    8. });  
    9. app.use(express.static('public')); //making public directory as static diectory   
    10. app.get('/'function(req, res) {  
    11.     res.send('<h1>Hello C# Corner.</h1>');  
    12. });  
    13. app.get('/articles'function(req, res) {  
    14.     res.send('<h1>Welcome to C# Corner Articles.</h1>');  
    15. });  

Our index.html file contains Bootstrap and jQuery. So, I want to use the latest version of Bootstrap and jQuery. Here, I am using "Bower" to use the latest version of Bootstrap and jQuery.

What is Bower?

Bower is a Package Manager for the web. npm is also package manager but this is Server-Side package manager. For front-end side, we have Bower. Bower keeps track of all the packages, making sure that they all are up to date. Bower can manage components that contain HTML, CSS, JavaScript, fonts or even image files. Bower doesn’t concatenate or minify the code or do anything else, as it just installs the right versions of the packages, which you need and their dependencies.

Using Bower

To use Bower in our project, you can use the steps, mentioned below.

  1. Install Bower from npm., using the command, mentioned below.

    node.js

  2. After installing Bower in package.json, we will get Bower dependency. The Bower folder will be installed in node_modules folder.

    node.js

  3. I am going to install Bower at a global level because Bower command can be accessed, using command prompt. To access Bower from the command prompt, I am installing it at global level.

    To install Bower at global level, just use the command, mentioned below.
    1. npm install bower - g  
  4. After installing Bower as global level, which is similar to package.json, we will create bower.json file. The command will be same like npm, which is similar to using Bower instead of npm,

    To create bower.json, just use the command, mentioned below.
    1. bower init  
    Similar to npm init command, this command will also ask some questions. Just press enter and keep it default.

    node.js

  5. Inside bower.json file, you will get the configuration, mentioned below.

    node.js

  6. As we have installed Bower, we want to install Bootstrap from bower. So, we will use the following command to download bootstrap
    1. bower install bootstrap--save  
    node.js

  7. After installing bootstrap, bower will create a directory named as "bower_components". 

    node.js

    You can see that bower has installed jQuery and Bootstrap in bower_components.

    Here, jQuery is automatically downloaded because bootstrap has dependency of jQuery.

  8. But, you can see that Bower installed all files in bower_components folder but our static directory is public. So, we need to specify bower to install files in public directory. To do that, just add a file ".bowerrc" and write the following code inside this file.
    1. {  
    2.     "directory""public/lib"  
    3. }  
    Now, save .bowerrc file and delete bower_components. And again, come to command prompt and type the following command.
    1. bower install bootstrap--save  
    After doing this, all the bower files will be installed in public/lib folder.

    node.js

  9. Now, I am modifying the Bootstrap and jQuery path from index.html.

Now, for testing purposes, I am also providing static path for src/view folder. The app.js code will be as follows.

app.js code

  1. var express = require('express');  
  2. var app = new express();  
  3. var port = 3000;  
  4. app.listen(port, function(err) {  
  5.     if (typeof(err) == "undefined") {  
  6.         console.log('Your application is running on : ' + port + ' port');  
  7.     }  
  8. });  
  9. app.use(express.static('public')); //making public directory as static diectory   
  10. app.use(express.static('src/views')); //making public directory as static diectory   
  11. app.get('/'function(req, res) {  
  12.     res.send('<h1>Hello C# Corner.</h1>');  
  13. });  
  14. app.get('/articles'function(req, res) {  
  15.     res.send('<h1>Welcome to C# Corner Articles.</h1>');  
  16. });  
Output

Following is the output for index.html file.

node.js

Thanks. In the next part, we will learn about GULP, Templating Engine EJS, Creating pages, Routing, Database connectivity etc.
Author
Praveen Moosad
Admin 48.3k 8.4m