Express and NodeJS Tutorial for Beginners

This tutorial is for Node.js and Express Beginners. Express is a node.js web development framework which comes with various features you require to build end-to-end web application such as routing, parsing, render engine support, etc.

In this tutorial, I am going to explain the Node.js along with the Express framework step by step. I request to perform these steps with me as and when you proceed with the tutorial.

Check out our most comprehensive and detailed tutorial about Node. It covers everything related to Node.js for Beginners.

We are going to cover the following in this Node.js tutorial:

  1. Understanding Project structure (Very important)
  2. Creating Package file and installing dependencies (such as Express or Mysql etc) using NPM.
  3. Creating Express Server.
  4. Creating Router to handle the request.
  5. Rendering HTML pages to deliver according to routing request (using EJS).

If you are new to Node and Express then you won’t regret taking our Node course. It’s FREE!

Make sure that you have installed Node in your system before proceeding ahead with the tutorial.

Node.js Download page link: Link.

OK, so let’s start!

Step 1: Understanding directory structure

This is very important because if you do not know the flow of the whole system and which file is running and where it is stored, what time it has been called then I am sure your understanding of code will not be up to mark.

Here is the directory structure of the sample project which I have made to demonstrate.

-------node_modules
-------router
-------------index.js
-------views
------------index.html
------------about.html
-------package.json
-------app.js

Now one question may arise in your mind? Do I have to create all these? The answer is No as well as Yes! You will be more clear about this in the next step.

Step2: Creating package.json

This is a JSON ( JavaScript object notation) file that contains every information about your project. Information may include Name, version, description, and may vary depending upon the project.

In package.json one of the important things is “dependencies” which is nothing but the tools you need to run your project. In our case, we want Express and EJS so we will mention those in our package.json file.

Go ahead and create a project folder (You can name it as per your choice). Switch to the folder using the Terminal application or command prompt and run the following command.

npm init --y

Upon execution, NPM will create a fresh package.json file. It may look different than what I am showing below.

{
  "name": "Express-web-app",
  "version": "1.0.0",
  "dependencies":{}
}

Let’s move ahead and install the dependencies.

Step 3 : Installing Dependencies using NPM

Open your command prompt or Terminal and install the dependencies using the following command.

npm install --save express

You can also install multiple dependencies at once. For example:

npm install --save express mysql ejs

NPM install

Just wait and let NPM do the rest !

Step 4: Create Express Server

Till this step we have installed dependencies and created package.json.  Now it’s time to create Express server to deal with Request and response by client. Go ahead and create file and save it as app.js and copy/paste this code in it.

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

app.listen(3000);
console.log("We have started our server on port 3000");

This is a basic express server that does nothing. If you will run “nodejs app.js” then on console it will show you message and on browser after typing localhost:3000 you will see nothing but a blank page and that’s because we have not defined the Router of our project yet.

Step 5: Router to handle Request

We have our Server ready along with every package we need. Now it’s time to tell our Server that on a request from browser what it has to do. That’s in a technical term called a Router which routes the application according to request.

Let’s create one simple router which respond to request and print “Hello world” on browser. Add this line in app.js before listen() function.

const express    =    require('express');
const app        =    express();
const router     =    express.Router();

router.get('/',(req,res) => {
    res.send('Hello world');
});

app.listen(3000);
console.log("We have started our server on port 3000");

Save the file and run the Server using

node app.js

and navigate to URL http://localhost:3000 in your browser. You may be able to see a message in your browser. This is just an example of a basic router.

routing process express

It is always a better practice to separate the router code and server code in different files. As i have shown in directory structure , create folder called “router” and inside that folder create “index.js” file and paste following code.

const express = require('express');
const router = express.Router();

router.get('/',(req,res) => {
    res.render('index.html')
});

router.get('/about',(req,res) => {
    res.render('about.html');
});

module.exports = router;

Save the file and do not run the code now. What is module.exports ? Since we have placed our code in a separate file and still want to use it in our Server file.

To do so we need to expose the functions which we want to use in a different file and that is what module.exports does.

Step 5: Render HTML page and send them in response

Now it’s time to do something complex stuff. Yes this is bit complex but i will explain it simply. The EJS package which we have defined in package.json file is allow us to render HTML pages. But before that i want you to create two HTML files named as “index” and “about” and put normal HTML codes.

Once done then in project directory create folder called as “VIEWS and put those HTML files in it.

Now it’s time to modify the Server file because we have made lots of changes in the project. Here is the modified and final Server file.

File name : server.js

const express  =  require('express');
const app  =  express();
const routes = require('./router/');

app.set('views',__dirname + '/views');
app.set('view engine', 'ejs');
app.engine('html', require('ejs').renderFile);

app.use('/', routes);

app.listen(3000);
console.log("Express is running on port 3000");
});

Notice some changes ! Yes we have additional four lines of code and those are as follows.

const routes = require('./router/');
app.set('views',__dirname + '/views');
app.set('view engine', 'ejs');
app.engine('html', require('ejs').renderFile);
app.use('/', routes);

Line 1 : we are basically adding our index.js which is our router file.

Line 2: This line defines where our HTML files are placed so that Server can locate and render them! Easy enough.

Line 3: This line set the view engine or simply presentation factor to EJS which is responsible for HTML rendering.

Line 4: This final line will tell Server that we are actually rendering HTML files through EJS.

Everything is done ! Let’s run

Okay, amigos! Let’s run the code. What you need to do is open up your Terminal and switch to our project directory. Then just type

node app.js

you should be able to see a message in the terminal that Server is running.

Open your browser and go to http://localhost:3000 and this is it. You may be able to see whatever you have placed in HTML pages.

Further Study

Render HTML file in ExpressJS
Node.js MySQL Tutorial
Node.js MongoDB Tutorial
Node.js and Redis tutorial – Building Email verification system