Node js and Express 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 Node.js tutorial for beginners, we are going to cover the following topics:

  1. Node.js Basic Concepts
  2. Installing Node.js in your system
  3. Express framework
  4. Express Routers
  5. Express Middlewares
  6. Creating a Web Server using Express.
  7. Express Sessions.
  8. Express File uploads
  9. Database interfacing with Node.js.
  10. Deployment of Node.js applications.

Let’s begin.

Node.js Basic Concepts

Node.js is a JavaScript runtime framework. Node.js runs on top of the V8 engine — Chrome runtime engine that compiles the JavaScript code in the native machine code followed by the custom C++ code.

Node.js uses various components to make the ends meet. Here are the unofficial architectural components of Node.

Nodejs Architecture

The V8 JavaScript engine is an open-source JavaScript engine developed for the Chrome project. The innovation behind V8 is that it compiles the JavaScript code in native machine code and executes it.

The libuv library is a cross-platform library that provides an asynchronous I/O facility by enabling an event-driven I/O operation. The libuv library creates a thread for the I/O operation (file, DNS, HTTP, and so on) and returns a callback.

The libuv library provides the following important core features:

  • A fully-featured event loop
  • Asynchronous filesystem operations
  • Thread pool
  • Thread and synchronization primitives
  • Asynchronous TCP and UDP sockets
  • Child process
  • Signal handling

The libuv library internally uses another famous library called libeio, which is designed for threading and asynchronous I/O events and libev, which is a high-performance event loop.

This is it for basics. if you want a deep dive into Node.js you should checkout out our detailed tutorial on Node mentioned below.

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

Installing Node in your system

To install Node.js in your system. Head over to the official website of Node.js downloads page and grab a copy of Node based on your operating system.

However, I highly recommend you install Node using the Node version manager. It’s a software that allows you to quickly switch between the Node.js version based on your needs.

Click here to navigate to the article to install Node using NVM.

Express Framework

Express is a web framework for Node.js. Using Express you can build web applications, REST APIs, frameworks quickly and efficiently.

First, create a new folder and initialize it with a blank package.json file using the command below.

npm init --y

To install the latest and stable version Express in your project, run the following command.

npm install --save express

Upon execution of this command, you will have the express framework installed in your project. Let’s create a sample code to test out Express framework.

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

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

app.listen(process.env.port || 3000);
console.log('Web Server is listening at port '+ (process.env.port || 3000));

Run this code using the following command.

node app.js

Navigate your browser to localhost:3000 to view the response of the web server.

Let’s learn about Express routers.

Express Routers

Routers are simply an endpoint of a server.

For example, facebook.com/codeforgeek, here the codeforgeek is a route.

We can perform various operations on routes using HTTP methods such as GET, POST, PUT, and DELETE.

Let’s learn by doing it. Refer to the code shown below.

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

router.get('/home', (req,res) => {
  res.send('Hello World, This is home router');
});

router.get('/profile', (req,res) => {
  res.send('
    Hello World, This is profile router
  '
);
});

router.get('/login', (req,res) => {
  res.send('
    Hello World, This is login router
  '
);
});

router.get('/logout', (req,res) => {
  res.send('
   Hello World, This is logout router
  '
);
});

app.use('/', router);

app.listen(process.env.port || 3000);

console.log('Web Server is listening at port '+ (process.env.port || 3000));

Let’s run our application, save the file, and run the code using the following command.

node app.js

You should see the following message in the terminal.

Web Server is listening at port 3000

Open your browser and visit the routes.

Nodejs tutorial for beginners step by step

You can also handle other HTTP methods such as GET and POST.

You can also send HTML/XML as a response in your routes.

Let’s learn about Express middlewares.

Express Middlewares

Middleware functions as the name suggests can be used to make changes in the request/response lifecycle of the express. Middleware functions execute before sending the response back to the user. You can use multiple middleware functions chained together and they execute in a order.

There are five types of middleware functions in the express.

  • Application middleware
  • Router middleware
  • Error-handling middleware
  • Built-in middleware
  • Third-party middleware

We can use application middleware using the instance of the express. For example:

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

app.use((req, res, next) => {
  console.log('Time:', Date.now());
  next();
});

app.listen(process.env.port || 3000);

console.log('Web Server is listening at port '+ (process.env.port || 3000));

In a similar way as application middleware, we can use router middleware. For example:

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

router.use((req, res, next) => {
  console.log('Time:', Date.now());
  next();
});

router.get('/home', (req,res) => {
  res.send("ok")
});

app.use('/', router);
app.listen(process.env.port || 3000);

console.log('Web Server is listening at port '+ (process.env.port || 3000));

We can use this middleware to catch errors.

app.use((err, req, res, next) => {
  res.status(500).send('Something broke!')
});

Learn more about this function by reading this article.

Express provides some middleware by default such as express.static(), express.json() and express.urlencoded().

We can use third-party middlewares built by awesome developers like you. Here is how we can install third-party middleware.

npm install --save body-parser

Here is how we can use this third-party express middleware.

const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const router = express.Router();

router.get('/home', (req,res) => {
  res.send('
   Hello World, This is home router
  '
);
});

router.get('/profile', (req,res) => {
  res.send('
   Hello World, This is profile router
  '
);
});

router.get('/login', (req,res) => {
  res.send('
   Hello World, This is login router
  '
);
});

router.get('/logout', (req,res) => {
  res.send('
   Hello World, This is logout router
  '
);
});

// add middleware before routes
app.use(bodyParser.json());

app.use('/', router);

app.listen(process.env.port || 3000);

console.log('Web Server is listening at port '+ (process.env.port || 3000));

Make sure that the order of middlewares is right. I have seen lots of developers making this mistake. Express will execute the middleware in the order it is initialized.

Express Sessions Management

Session management is a crucial part of the web application. We can use third-party middleware to achieve the session functionality in the Express framework.

Let’s install the middleware.

npm install --save express express-session body-parser

Here is a sample code to achieve sessions in Express.

const express = require('express');
const session = require('express-session');
const bodyParser = require('body-parser');
const router = express.Router();
const app = express();

app.use(session({secret: 'ssshhhhh',saveUninitialized: true,resave: true}));
app.use(bodyParser.json());      
app.use(bodyParser.urlencoded({extended: true}));

var sess; // global session, NOT recommended, only for demonstration purpose

router.get('/',(req,res) => {
    sess = req.session;
    if(sess.email) {
        return res.redirect('/admin');
    }
    res.send('Ok');
});

router.post('/login',(req,res) => {
    sess = req.session;
    sess.email = req.body.email;
    res.end('done');
});

router.get('/admin',(req,res) => {
    sess = req.session;
    if(sess.email) {
        res.write(`<h1>Hello ${sess.email} </h1><br>`);
        res.end('<a href='+'/logout'+'>Logout</a>');
    }
    else {
        res.write('<h1>Please login first.</h1>');
        res.end('<a href='+'/'+'>Login</a>');
    }
});

router.get('/logout',(req,res) => {
    req.session.destroy((err) => {
        if(err) {
            return console.log(err);
        }
        res.redirect('/');
    });

});

app.use('/', router);

app.listen(process.env.PORT || 3000,() => {
    console.log(`App Started on PORT ${process.env.PORT || 3000}`);
});

In the code shown above, there are four routers. First, which renders the home page, the second router is used for a login operation. We are not doing any authentication here for the sake of simplicity.

The third router is used for the admin area where the user can only go if he/she is log-in. The fourth and the last router is for session destruction.

In a production scenario, we should always use a external session store so that sessions are not shared for every user ( Like we did above for the sake of an explanation ).

Read this article to build a session-based applications using external session stores such as Redis.

There is another alternative to sessions that is widely used in mobile applications. It’s a token-based authentication. We have covered the token-based authentication in the detail in this article.

File uploads in Express

To handle file uploads in the Express framework, we need to use the popular node module called multer.

First, install multer using the following command.

npm install --save express body-parser multer

Refer to the code below to handle file uploads in the Express framework.

var express = require("express");
var bodyParser = require("body-parser");
var multer = require('multer');
var app = express();

app.use(bodyParser.json());

var storage = multer.diskStorage({
  destination: function (req, file, callback) {
    callback(null, './uploads');
  },
  filename: function (req, file, callback) {
    callback(null, file.fieldname + '-' + Date.now());
  }
});

var upload = multer({ storage : storage }).array('userPhoto',2);

app.post('/api/photo',function(req,res){
    upload(req,res,function(err) {
        if(err) {
            return res.end("Error uploading file.");
        }
        res.end("File is uploaded");
    });
});

app.listen(3000,function(){
    console.log("Working on port 3000");
});

First, we initialized the multer with the disk storage i.e we are going to save our files in the machine where our Node server is running.

var storage = multer.diskStorage({
  destination: function (req, file, callback) {
    callback(null, './uploads');
  },
  filename: function (req, file, callback) {
    callback(null, file.fieldname + '-' + Date.now());
  }
});

var upload = multer({ storage : storage }).array('userPhoto',2);

The userPhoto is the key that should be used in the HTML file element as an ID. Then, we simply called this function in the router.

    upload(req,res,function(err) {
        if(err) {
            return res.end("Error uploading file.");
        }
        res.end("File is uploaded");
    });

Read this article to learn file uploads in Express in the detail.

Let’s learn about the interfacing databases in Node applications.

Node and Databases

The database is an integral part of any application. You must know how to use it with Node to build a complete application.

Let’s begin with interfacing Node with MySQL.

MySQL is a very popular database and has been used in millions of applications. We can use MySQL with Node as well.
We need to install the module name as mysql to use it with the MySQL database.

First, you need to install the MySQL server in your system.

Let’s install the node module.

npm install --save mysql

Assuming you have MySQL running in your system, you can use the following code to connect to it.

const mysql = require("mysql");

const pool = mysql.createPool({
 connectionLimit: 100,
 host: "localhost",
 user: "root",
 password: "",
 database: "database_name",
 debug: false,
});

pool.query("SELECT * from table_name LIMIT 10", (err, rows) => {
 if (err) {
   console.log("error occurred during the connection.");
 }
 console.log(rows[0]);
});

Replace the database and table name with the actual one in your system.

You can execute queries such as INSERT, UPDATE, and DELETE in a similar fashion. Learn more in detail about using Node and MySQL.

Deployment of Node applications

Once you are finished with your application, it’s time to test it out in the cloud server. I use and host every project in the DigitalOcean cloud platform. It’s easy, affordable, and made for developers.

Refer to this tutorial to deploy Node application in the DigitalOcean platform.

Summary

Node.js is a popular framework and used in tons of companies. In fact, we built this website using Node and Express. I highly recommend you to learn it in and out to upskill and expand your portfolio. I hope this Node.js tutorial is helpful to you. Please provide your feedback in the comment section.