Node.js Tutorial for Beginners 2021

In this article, we discuss Node.js Tutorial for Beginners 2021

Node.js Tutorial for Beginners 2021

Node.js Tutorial for Beginners 2021
Node.js Tutorial for Beginners 2021

Node.js Tutorial for Beginners 2021

JavaScript is a prominent language that dominated the market of front-end development since ages. It is a powerful scripting language that helps in developing client-side applications but it failed when there was a necessity to execute applications on the server-side. This is where Node.js comes in and provides a better feature set. By the time you finish reading this article, you will be having a complete understanding of what is Node.js and why it is so popular in the market. 

Below are the topics covered in this what is Node.js article:

  • What is Node.js?
  • Node.js Architecture
  • Advantages of Node.js
  • Applications of Node.js
  • Simple Node.js Demo
  • NPM (Node Package Manager)
  • Node.js Modules
  • JSON File
  • Node.js Basics
  • File System
  • Events
  • HTTP Module
  • Express.js
  • Node.js Tutorial Step By Step Application Development with Express.js

What is Node.js?

Node.js is a powerful JavaScript framework that is developed on Chrome’s V8 JavaScript engine. It helps in compiling JavaScript directly into the native machine code. It is light in weight and is heavily used in the market for developing server-side web applications. Node.js extends JavaScript API which enables the usual server-side functionalities as well. It is generally used for large-scale application development, especially for video streaming sites, single-page application, and other web applications. Node.js makes use of an event-driven, non-blocking I/O model which makes it a right pick for the data-intensive real-time applications.

Like any other programming languages, Node.js makes use of various packages and modules. These are nothing but the libraries containing functions and are imported from npm (node package manager) into our code and utilized in the programs. But in order to understand Node.js in more detail, first, you need to know how it works internally.

Node.js Tutorial for Beginners 2021

In the next section of this What is Node.js article, I will get into the details of its architecture.

Node.js Architecture

Generally, the server-side technologies like PHP, ASP.NET, Ruby & Java Servers all follow a multi-threaded model. In this traditional architectural approach, each client request creates a new thread or a process.

What is a JavaScript Variable and How to declare it 2
Node.js Tutorial for Beginners 2021

To avoid this, Node.js uses Single Threaded Event Loop Model Architecture. It means that all the client requests on Node.js are executed on the same thread. But this architecture is not just single-threaded, but event-driven as well. It helps Node.js in handling multiple clients concurrently. Below diagram, represents the Single Threaded Event Loop Model architecture.

As you can see in the diagram, the main event loop is single-threaded whereas the I/O workers are executed on distinct threads. This is done to accommodate the entire event loop where most of the Node.js API‘s are designed to be asynchronous/non-blocking. This reduces the server response time and increases application throughput.

I hope this clears the internal functioning of Node.js. Let now move further in this ‘What is Node.js’ article and find out various advantages of using Node.js for application development.

Node.js Tutorial for Beginners 2021

Advantages of Node.js

  • Easy to Scale

Node.js is mostly preferred by the developers as it is easy to scale the applications developed with Node.js, in horizontal as well as the vertical direction. Also, you can easily assign extra resources to it while scaling the app.

  • Real-Time Web Applications

The applications developed in Node.js provides a faster synchronization and because of its single-threaded architecture HTTP overload is also reduced. This is the main reason developers prefer Node.js for developing web-based chat and gaming applications.

  • Faster Suite

As you know by now, Node.js runs on the top of Google’s V8 engine which by far is the fastest JavaScript engine. Node.js makes use of npm which is an online repository for libraries and tools. Because of npm, the code execution of Node.js application is way faster when compared with other technologies.

  • Easy to Learn

Anyone having a brief knowledge about JavaScript can learn to code in Node.js easily as it is a JavaScript framework. The learning curve of Node.js is very shallow and it is less complex to learn and use its various libraries and toolkits.

  • Single Programming Language

Node.js can single-handedly build web applications for both, front-end as well as the back-end. Because of this, the deployment of web applications has become a lot easier as most of the web browsers support JavaScript.

  • Caching

Node.js enables the functionality of caching of a single module. As a result, you don’t have to re-execute the code, each time a request for the first module is generated.

  • Data Streaming

Since HTTP requests and responses are considered to be two separate modules in Node.js, they are treated as two separate data streams. Now each time these files are loaded, the overall processing time decreases resulting in better efficiency. Thus, you can stream audios and videos without having to wait for long.

  • Hosting

Deployment the Node.js applications has also become very easy with the help of hosting platforms such as PaaS (Platform as a Service) and Heroku.

  • Support of Large and Active Community

Node.js is backed up by a large and active community of developers. They continuously contribute towards its further development and improvement and come up with innovative solutions.

Let’s now move further with this what is Node.js article, and see the various applications of Node.js in today’s market.

Node.js Tutorial for Beginners 2021

Applications of Node.js

Node.js tops the popularity chart when compared with other frameworks, libraries, and tools.

Below are the applications which are mostly developed in Node.js:

  • Real-Time Chats
  • Complex Single-Page Applications
  • Real-time collaboration tools
  • Live Streaming Applications
  • JSON APIs based Applications

Now that you know about the areas of application of Node.js, let’s check out the list of the major brands in the market using Node.js in their production:

  1. Netflix
  2. Linkedin
  3. Trello
  4. Uber
  5. PayPal
  6. Medium
  7. eBay
  8. NASA
  9. Groupon
  10. Walmart
Node.js Tutorial for Beginners 2021

Now, in order to understand what is Node.js better, let’s take a look at its practical implementation.

Node.js Tutorial for Beginners 2021

Demo with Node.js

In order to get your feet wet with Node.js, first, you need to have the Node.js environment installed in your system. To install it, in your system.

Once done, all you need to do is, open the command prompt and navigate to your project directory. There you need to type in the following command.

npm init

As soon as you hit enter, you will be asked a few questions related to your project file

Once you provide the details and hit ‘Enter’ your  package.json file will be created having details of your project. It should look like below:

  "name": "nodeintro",
  "version": "1.0.0",
  "description": "What is Node.js Demo",
  "main": "script.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  "author": "thestackoverflow",

Node.js Tutorial for Beginners 2021

Now, the next step is to create the entry point of your application. In order to create this file, type in the below-given code and name the file as you have specified in the json file:

const http = require('http');
const hostname = '';
const port = 8080;
const server = http.createServer((req, res) => {
    res.statusCode = 200;
    res.setHeader('Content-Type', 'text/plain');
    res.end('Welcome to Edureka's Tutorial');
server.listen(port, hostname, () => {
    console.log(`Server running at http://${hostname}:${port}/`);

Node.js Tutorial for Beginners 2021

Features of Node.js

  1. Open Source
    Node.js is an open source framework MIT license that is supported by a huge community. Its community is pretty much active have contributed to add new capabilities to Node.js applications.
  2. Simple and Fast
    Since Node.js is built on Google Chrome’s V8 JavaScript Engine, its libraries are capable of fast code execution.
  3. Asynchronous
    All the libraries of Node.js are asynchronous which means the Node.js based servers never wait for an API to send back the response and move on to the next API.
  4. High Scalability
    Because of the event mechanism, Node.js is highly scalable and aids the server in a non-blocking response.
  5. Single-Threaded
    With the help of event looping, Node.js is able to follow the single-threaded model. This lets a single program to handle multiple requests.
  6. No Buffering
    One of the major functionalities of Node.js applications is that it never buffers any data.
  7. Cross-Platform
    Node.js can be easily built and deployed on various platforms like Windows, MAC, and Linux.

Node.js Tutorial for Beginners 2021

NPM (Node Package Manager)

NPM stands for Node Package Manager which as the name suggests is a package manager for Node.js packages/modules. From Node version 0.6.0. onwards, npm has been added as default in the node installation. It saves you from the hassle of installing npm explicitly.

NPM basically helps in two ways:

  1. Provides and hosts Online repositories for node.js packages/modules which can be easily downloaded and used in our projects. You can find them here:
  2. Provides the Command line utility in order to install various Node.js packages, manage Node.js versions and dependencies of the packages.

But now, you must be wondering what exactly these modules are and how do they help us in building the Node.js applications. Well, in the next section of this Node.js tutorial, I will give you a complete insight into Node.js modules.

Node.js Tutorial for Beginners 2021

Node.js Modules

The modules in Node.js represents various functionalities that are bundled up into single or multiple JS files. These modules have a unique context, thus, they never interfere nor pollute the scope of other modules.

These modules enable the code reusability and enhance the ease of usage. Node.js basically provides three types of modules:

  1. Core Modules
  2. Local Modules
  3. Third-Party Modules

Core Module

Since Node.js is a very lightweight framework, the core modules bundle the absolute minimum functionalities. These modules generally get loaded when the Node process starts its execution. All you need to do is, import these core modules in order to use them in your code.

Below I have listed down a few of the important Core modules.

Core Module Description
httpContains classes, methods, and events required to create Node.js HTTP server
urlContains methods for URL resolution and parsing in Node
querystringContains methods to deal with a query string of Node
pathContains methods to deal with file paths
fsContains classes, methods, and events to work with file I/O
utilContains utility functions that can be useful for programmers
Node.js Tutorial for Beginners 2021

You can load your core module, using the below code:

var module = require('module_name');

Node.js Tutorial for Beginners 2021

Lets now see, what are ‘local modules’.

Local Modules

The local modules of Node.js are custom modules that are created locally by user/developer in the application. These modules can include various functionalities bundled into distinct files and folders which can be easily distributed in the Node.js community using NPM.

These modules are loaded in a similar way to core modules. Let show you, how to do it using a basic example.

Create your custom/local-module.js file

var detail = {
  name: function (name) {
    console.log('Name: ' + name);
  domain:function (domain) {
    console.log('Domain: ' + domain);
module.exports = detail;

Node.js Tutorial for Beginners 2021

Include your module file in your main application file.

var myLogModule = require('./Local_module.js');'Edureka');

Node.js Tutorial for Beginners 2021

Now you can execute these files using below command:

node application.js

Let me now show you what are external modules.

External Modules

You can use the external or 3rd party modules only by downloading them via NPM. These modules are generally developed by other developers and are free to use. Few of the best external modules are express, react, gulp, mongoose, mocha etc.

Globally Loading the 3rd party modules:

npm install --g <module_name>

Include your module file in your main application file:

npm install --save <module_name>

Node.js Tutorial for Beginners 2021


The package.json file in Node.js is the heart of the entire application. It is basically the manifest file that contains the metadata of the project. Thus, understanding and working with this file becomes very important for a successful Node project development.

The package.json file generally consists of the metadata of the application, which is further categorized into below two categories:

  1. Identifying metadata properties: This consists of properties like the project name, current module version, license, author of the project, project description etc.
  2. Writing directly to file: You can directly write the necessary information into the package.json file and include it, in your project.

By now you have already familiarized with the various components of Node JS application. In the next section of this Node.js Tutorial, I will be sharing some Node Js basics so that we can start off with the hands on.

Node.js Basics

Since Node.js is a JavaScript framework, it uses the JavaScript syntax. If you want to learn JavaScript in detail, you can refer to this JavaScript Tutorial. For now, I will be brushing you up with some Node.js basics like:

Data Types

Like any other programming language, Node.js has various datatypes, which are further categorized into Primitive and Non-Primitive datatypes.

Primitive Data Types are:

  1. String
  2. Number
  3. Boolean
  4. Null
  5. Undefined

Non-Primitive Data Types are:

  1. Object
  2. Date
  3. Array


Variable are entities that hold values which may vary during the course of a program. To create a variable in Node.js, you need to make use of a reserved keyword var. You do not have to assign a data type, as the compiler will automatically pick it.


1var varName = value;


Node.js supports the below operators:

Operator TypeOperators
Arithmetic+, -, /, *,  %, ++, —
Assignment=, +=, -=, *=, /=, %=
Comparison==, ===, !=, !==, >, >=, <, <=,
Logical&&, ||, !
Bitwise&, |, ^, ~, <<, >>, >>>
Node.js Tutorial for Beginners 2021


Functions in Node.js is a block of code that has a name and is written to achieve a particular task. You need to use the keyword function to create it. A function is generally a two-step process. First is defining the function and the second is invoking it. Below is the syntax of creating and invoking a function:


//Defining a function
function display_Name(firstName, lastName) {
  alert("Hello " + firstName + " " + lastName);
//Invoking the function
display_Name("Madhu", "Arun");

Node.js Tutorial for Beginners 2021


An object is a non-primitive data type that can hold multiple values in terms of properties and methods. Node.js objects are standalone entities as there is no concept of class. You can create an object in two ways:

  1. Using Object literal
  2. Using Object constructor


var employee = {
  firstName: "Minho",
  lastName: "Choi",
  age: 35,
  getFullName: function () {
    return this.firstName + ' ' + this.lastName

Node.js Tutorial for Beginners 2021

File System

To access the physical file system, Node.js makes use of the fs module which basically takes care of all asynchronous and synchronous file I/O operations. This module is imported using the below command:

var fs = require('fs');

Node.js Tutorial for Beginners 2021

Some of the general use for the File System modules are:

  • Read files
    1. fs.readFile()
var http = require('http');
var fs = require('fs');
http.createServer(function (req, res) {
  fs.readFile('script.txt', function(err, data) {
    res.writeHead(200, {'Content-Type': 'text/html'});

Node.js Tutorial for Beginners 2021

  • Create files
    1. appendFile()
    2. open()
    3. writeFile()
  • Update files
    1. fs.appendFile()
    2. fs.writeFile()
  • Delete files
    1. fs.unlink()
  • Rename files
    1. fs.rename()

So, with these commands, you can pretty much perform all the required operations on your files. Let’s now move further with this Node.js Tutorial and see what are Events and how they are handled in Node.js.

Node.js Tutorial for Beginners 2021


As I have already mentioned, Node.js applications are single threaded and event-driven. Node.js supports concurrency as it is event-driven, and thus makes use of concepts like events and callbacks. The async function calls help Node.js in maintaining concurrency throughout the application.

Basically, in a Node.js application, there is a main loop which waits and listens for events, and once any event is completed, it immediately initiates a callback function.

Below diagram represents how the events are driven in Node.js.

event loop
Node.js Tutorial for Beginners 2021

One thing that you must note here is that, even though events look similar to callback functions but the difference lies in their functionalities. When an asynchronous function returns its results callbacks are invoked on the other hand event handling completely works on the observer pattern. And in Node.js, methods which listen to the events are called the observers. The moment, an event is triggered, its listener function automatically starts executing. Event modules and EventEmitter class provide multiple in-built events which are used to bind events with event listeners. Below I have written down the syntax for that.

Binding Event to an Event Listener

// Import events module
var my_Events = require('events');
// Create an eventEmitter object
var my_EveEmitter = new my_Events.EventEmitter();

Binding Event Handler to an Event

// Binding event and event handler 
my_EveEmitter.on('eventName', eventHandler);

Node.js Tutorial for Beginners 2021

Firing an Event 

// Fire an event

Now let’s try to implement the things that I have discussed in this Node.js Event section. The below code shows a simple representation of Event execution in Node.js.

var emitter = require('events').EventEmitter;
function iterateProcessor(num) {
  var emt = new emitter();
  setTimeout(function () {
        for (var i = 1; i <= num; i++) {
          emt.emit('BeforeProcess', i);
          console.log('Processing Iteration:' + i);
          emt.emit('AfterProcess', i);
      , 5000)
  return emt;
var it = iterateProcessor(5);
it.on('BeforeProcess', function (info) {
  console.log('Starting the process for ' + info);
it.on('AfterProcess', function (info) {
  console.log('Finishing processing for ' + info);

In the next section of this Node.js Tutorial, I will give you insights on one of the most important module of Node.js called the HTTP Module.

Node.js Tutorial for Beginners 2021

HTTP Module

Generally, Node.js is used for developing server-based applications. But using the module, you can easily create web servers that can respond to the client requests. Thus it is also referred to Web Module and provides modules like HTTP and request that facilitate Node.js in processing the server requests.

You can easily include this module in your Node.js application just by writing the below code:

var http = require('http');

Below I have written a code, that shows how a Web Server is developed in Node.js.

//calling http library
var http = require('http');
var url = require('url');
//creating server
var server = http.createServer(function (req, res) {
  //setting content header
  res.writeHead(200, ('Content-Type', 'text/html'));
  var q = url.parse(req.url, true).query;
  var txt = q.year + " " + q.month;
  //send string to response
//assigning 8082 as server listening port

In the next section of this Node.js Tutorial, I will be talking about Express.js which is heavily used for server-side web application development.

Node.js Tutorial for Beginners 2021


Express.js is a framework built on top of Node.js that facilitates the management of the flow of data between server and routes in the server-side applications.  It is a lightweight and flexible framework that provides a wide range of features required for the web as well as mobile application development.

Express.js is developed on the module of Node.js called connect. The connect module further makes use of http module to communicate with Node.js. Thus, if you are working with any of the connect based middleware modules, then you can easily integrate with Express.js.

 Not, only this, few of the major advantages of Express.js are:

  • Makes web application development faster
  • Helps in building mobile and web application of single-page, multi-page, and hybrid types
  • Express provides two templating engines namely, Jade and EJS
  • Express follows the Model-View-Controller (MVC) architecture
  • Makes integration with databases such as MongoDB, Redis, MySQL
  • Defines an error handling middleware
  • Simplifies configuration and customization easy for the application.

With all these features, Express takes responsibility of backend part in the MEAN stack. Mean Stack is the open-source JavaScript software stack that is used for building dynamic websites and web applications. Here, MEANstands for MongoDB, Express.js, AngularJS, and Node.js.

Lets now see a simple example to understand, how Express.js works with Node.js to ease our work. But before you start working with Express.js, you need to install it in your system.

To install Express.js globally you can use the below command:

npm install -g express

Or, if you want to install it locally into your project folder, you need to execute the below command:

npm install express --save

Since we are done with all the preparations, let’s now jump directly into practical implementation. Here, I will be showing a simple User Authentication Application using Node.js and Express.js.

Node.js Tutorial for Beginners 2021

Node.js Tutorial Step By Step Application Development with Express.js

For this, we will be needing below files:

  • package.json
  • script.js
  • views
    • index.jade
    • login.jade
    • secure.jade
    • unauthorized.jade
    • welcome.jade
  • lib
    • routes.js

So, let’s start with package.json.

  "author": "thestackoverflow",
  "name": "Express-Demo",
  "description": "Express with Node.js",
  "version": "0.0.0",
  "scripts": {
    "start": "node script.js"
  "engines": {
    "node": "~0.4.12"
  "dependencies": {
    "connect-flash": "^0.1.1",
    "cookie-parser": "^1.4.3",
    "express": "^3.21.2",
    "jade": "^0.20.3",
    "req-flash": "0.0.3"
  "devDependencies": {}

Node.js Tutorial for Beginners 2021

Next, you need to create the script.js.

var express = require('express');
var http = require('http');
var port = 8999;
var app = express();
const flash = require('connect-flash');
var cookieParser = require('cookie-parser')
var server = http.createServer(app);

function checkAuth (req, res, next) {
   console.log('checkAuth ' + req.url);

   // don't serve /secure to those not logged in
   if (req.url === '/secure' && (!req.session || !req.session.authenticated)) {
      res.render('unauthorised', { status: 403 });

   app.use(express.session({ secret: 'example' }));
   app.set('view engine', 'jade');
   app.set('view options', { layout: false });


console.log('Node listening on port %s', port);

Node.js Tutorial for Beginners 2021

Now, create a folder named view, under which you will be adding the jade files that will be responsible for various page views. The first view file you need to create is index.jade.

!!! 5
      title User Authentication
      <link href="" rel="stylesheet"/>

         center Authentication Demo using Express
         h3 Navigate to
            li: a(href="/secure") Secure content
            li: a(href="/welcome") Welcome page
            li: a(href="/logout") Logout

Node.js Tutorial for Beginners 2021

Now, create the login.jade file.

!!! 5
      title Express authentication 
      <link href="" rel="stylesheet"/>
         center Sign-in to this Express authentication example
         p Use <i>user</i> for the username and <i>pass</i> for the password.

            label(for='username') Email Address
            input(type='text', name='username', class='form-control', id='exampleInputPassword1' , placeholder='Email', style='width:400px;')
            label(for='password') Password
            input(type='password', name='password', class='form-control' , id='exampleInputPassword1', placeholder='Password', style='width:400px;')

            center <button type="submit" class="btn btn-info">Submit</button>
      - each message in flash
         h4(style="color: red;") #{message}

Node.js Tutorial for Beginners 2021

Next step is to create the welcome.jade.

!!! 5
      title User Authentication 
      <link href="" rel="stylesheet" />
         center User Authentication 

Node.js Tutorial for Beginners 2021

Next, create the secure.jade file.

!!! 5
      title Express Authentication 
      <link href="" rel="stylesheet" />
         center Hi, user.
      p Navigate to
            li: a(href="/secure") Secure content
            li: a(href="/welcome") Welcome page
            li: a(href="/logout") Logout

Node.js Tutorial for Beginners 2021

Now, create the unauthorized.jade file.

!!! 5
      title User Authentication 
      <link href="" rel="stylesheet" />
         center Unauthorized
      p You're unauthorized to view this page.
      p Please <a href="/login" class="btn btn-success">login</a> to continue

Node.js Tutorial for Beginners 2021

Now, you need to create a folder and name it lib. Now, create a route.js file which will map all the pages.

var util = require('util');
module.exports = function (app) {
   app.get('/', function (req, res, next) {

   app.get('/welcome', function (req, res, next) {

   app.get('/secure', function (req, res, next) {

   app.get('/login', function (req, res, next) {
      res.render('login', {flash: req.flash() } );
   });'/login', function (req, res, next) {

      // you might like to do a database look-up or something more scalable here
      if (req.body.username && req.body.username === 'user' && req.body.password && req.body.password === 'pass') {
         req.session.authenticated = true;
      } else {
         req.flash('error', 'Username and password are incorrect');

   app.get('/logout', function (req, res, next) {
      delete req.session.authenticated;


Node.js Tutorial for Beginners 2021

We are Coming up the end of Node.js Tutorial for Beginners 2021. I hope I was able to explain the concepts of Node.js from the ground up. 

Source: Various

Also Check out ExpressJS Tutorial for Beginners 2021

If you interested in Entertainment genre please check this also Prabhas Age, Biography, Wiki, Family, Filmography & More

Related Posts

Leave a Reply

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