Mastering Node.js (19 Blogs) Become a Certified Professional

Node.js Tutorial – A Complete Guide For Beginners

Last updated on Aug 18,2022 34.2K Views

Swatee Chand
Sr Research Analyst at Edureka. A techno freak who likes to explore... Sr Research Analyst at Edureka. A techno freak who likes to explore different technologies. Likes to follow the technology trends in market and write...
2 / 4 Blog from Introduction to Node.Js

If you have ever heard about Node.js then you might know that it is one the most prominent and powerful frameworks of JavaScript. Since its release, it has continued to keep its stranglehold on the IT market. Even with the introduction of new and vibrant JS Frameworks like Angular, React, Meteor etc., the popularity of Node.js never seems to cease. Wondering why? Well, with the help of this Node.js Tutorial, I will be giving you a complete insight into it. So, get ready to fall in love with Node.js.

In this Node.js Tutorial, I will be discussing the below topics:

What is Node.js?

Node.js is a powerful framework developed on Chrome’s V8 JavaScript engine that compiles the JavaScript directly into the native machine code. It is a lightweight framework used for creating server-side web applications and extends JavaScript API to offer usual server-side functionalities. 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 packages and modules. These are the libraries that contain various functions and are imported from npm (node package manager) into our code and utilized in the programs. Some of the major features, that define Node.js are listed below:

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.

Let’s now advance further and see how to deploy the actual code on the browser. But before that, you need to download and install in your systems. You can refer my other article to know the complete Node.js installation process.

So now, let’s move further in this Node.js Tutorial, where I will talk about the most important component of Node.js i.e., npm.

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: npmjs.com
  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 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

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

var module = require('module_name');

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;

Include your module file in your main application file.

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

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>

JSON File

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.
  1. 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

Variables

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.

Syntax:

var varName = value;

Operators

Node.js supports the below operators:

Operator TypeOperators
Arithmetic+, -, /, *,  %, ++, —
Assignment=, +=, -=, *=, /=, %=
Conditional=?
Comparison==, ===, !=, !==, >, >=, <, <=,
Logical&&, ||, !
Bitwise&, |, ^, ~, <<, >>, >>>

Functions

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:

Example:

//Defining a function
function display_Name(firstName, lastName) {
  alert("Hello " + firstName + " " + lastName);
}

//Invoking the function
display_Name("Park", "Jimin");

Objects

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

Example:

// object with properties and method
var employee = {
  //properties
  firstName: "Minho",
  lastName: "Choi",
  age: 35,
  salary:50000,
  //method
  getFullName: function () {
    return this.firstName + ' ' + this.lastName
  }
};

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');

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'});
    res.write(data);
    res.end();
  });
}).listen(8080);
  • 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.

Events

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.

Thread Model - Node.js Tutorial - Edureka

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);

Firing an Event 

// Fire an event
my_EveEmitter.emit('eventName'); 

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 &lt;= 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.

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
  res.end(txt);
});

//assigning 8082 as server listening port
server.listen(8082);

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.

Express.js

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 middleware 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 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": "Edureka",
  "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": {}
}

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 });
      return;
   }

   next();
}
   app.use(flash());
   app.use(cookieParser());
   app.use(express.session({ secret: 'example' }));
   app.use(express.bodyParser());
   app.use(checkAuth);
   app.use(app.router);
   app.set('view engine', 'jade');
   app.set('view options', { layout: false });

require('./lib/routes.js')(app);

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

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
html(lang='en')
   head
      title User Authentication Example
      <link href="https://stackpath.bootstrapcdn.com/bootswatch/4.2.1/darkly/bootstrap.min.css" rel="stylesheet" integrity="sha384-F7cPHYSdE3FzBKvdxDKyFow9Y28Yq7KGHQOKpOI+rwc8s6jJnp///mpEJAib2EM6" crossorigin="anonymous">

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

Now, create the login.jade file.

!!! 5
html(lang='en')
   head
      title Express authentication example
      <link href="https://stackpath.bootstrapcdn.com/bootswatch/4.2.1/darkly/bootstrap.min.css" rel="stylesheet" integrity="sha384-F7cPHYSdE3FzBKvdxDKyFow9Y28Yq7KGHQOKpOI+rwc8s6jJnp///mpEJAib2EM6" crossorigin="anonymous">
   body
      h1
         center Sign-in to this Express authentication example
      center
         p Use <i>user</i> for the username and <i>pass</i> for the password.

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

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

Next step is to create the welcome.jade.

!!! 5
html(lang='en')
   head
      title User Authentication Example
      <link href="https://stackpath.bootstrapcdn.com/bootswatch/4.2.1/darkly/bootstrap.min.css" rel="stylesheet" integrity="sha384-F7cPHYSdE3FzBKvdxDKyFow9Y28Yq7KGHQOKpOI+rwc8s6jJnp///mpEJAib2EM6" crossorigin="anonymous">
   body
      h1
         center Welcome To The Edureka Tutorial!

Next, create the secure.jade file.

!!! 5
html(lang='en')
   head
      title Express Authentication Example
      <link href="https://stackpath.bootstrapcdn.com/bootswatch/4.2.1/darkly/bootstrap.min.css" rel="stylesheet" integrity="sha384-F7cPHYSdE3FzBKvdxDKyFow9Y28Yq7KGHQOKpOI+rwc8s6jJnp///mpEJAib2EM6" crossorigin="anonymous">
   body
      h1
         center Hi, secure user.
      p Navigate to
         ul
            li: a(href="/secure") Secure content
            li: a(href="/welcome") Welcome page
            li: a(href="/logout") Logout

Now, create the unauthorized.jade file.

!!! 5
html(lang='en')
   head
      title User Authentication Example
      <link href="https://stackpath.bootstrapcdn.com/bootswatch/4.2.1/darkly/bootstrap.min.css" rel="stylesheet" integrity="sha384-F7cPHYSdE3FzBKvdxDKyFow9Y28Yq7KGHQOKpOI+rwc8s6jJnp///mpEJAib2EM6" crossorigin="anonymous">
   body
      h1
         center Unauthorized
      p You're unauthorized to view this page.
      p Please <a href="/login">login</a> to continue

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) {
      res.render('index');
   }); 

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

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

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

   app.post('/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;
         res.redirect('/secure');
      } else {
         req.flash('error', 'Username and password are incorrect');
         res.redirect('/login');
      }
   });

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

};

Now if you want to execute this code on your own then you can download it from here: Node.js Tutorial PDF.

With this, we come to an end of this Node.js Tutorial. I hope I was able to explain the concepts of Node.js from the ground up. 

If you found this “Node.js Tutorial” relevant, check out the Node JS Course by Edureka, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe. 

Got a question for us? Please mention it in the comments section of this Node.js Tutorial and we will get back to you.

Upcoming Batches For Node.js Certification Training Course
Course NameDate
Node.js Certification Training Course

Class Starts on 4th March,2023

4th March

SAT&SUN (Weekend Batch)
View Details
Comments
1 Comment
  • csps1343 says:

    Great stuff, Caleb. So many awesome post ideas. We at CSPS Protocol also provides node js tutorial and training services. Thanks

Join the discussion

Browse Categories

webinar REGISTER FOR FREE WEBINAR
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP

Subscribe to our Newsletter, and get personalized recommendations.

image not found!
image not found!

Node.js Tutorial – A Complete Guide For Beginners

edureka.co