Know about Node.JS: A beginner’s guide
Do you want to build browser games, chat rooms, real-time applications, APIs, and scalable applications with non-blocking and event-driven servers?
Accelerate your web development skills by learning the Best Node.JS Course in Chennai as Node.JS provides the Best JavaScript runtime platform.
In this article, we present you with fundamental and complete insight into Node.JS with real-time examples.
What is Node.JS?
Node.JS is one of the Best frameworks of JavaScript that helps in running the program in a run-time environment that compiles the JavaScript into the native machine code directly.
It is used for building non-blocking and event-driven server-side web applications by extending JavaScript API to provide the best server-side capabilities.
It is well-suited for large and scalable application development like video streaming sites and SPAs (Single Page Applications).
Its event-driven features make it the best for data-intensive real-time web application development.
Features of Node.JS
Node.JS has numerous features like thousands of libraries with packages and modules and they are collectively known as NPM (Node Package Manager) to serve for various functions to be deployed instantly by utilizing the pre-tested codes.
Following are the unique features of Node.JS
- Open-Source Availability under MIT license
- Simple and Fast as it is built on Google Chrome’s V8 JavaScript Engine
- Asynchronous for a move to the next API without waiting for a response from servers
- High Scalability that helps in a non-blocking response
- Single-Threaded for event looping to manage multiple requests
- No Buffering for streaming real-time data efficiently
- Cross-Platform that can be used in any operating system.
NPM (Node Package Manager)
NPM contains packages and modules of Node.JS and it is the default in the Node.JS installation. It helps users in two ways as follows
- Host Online Repositories: It allows you to download and utilize in your projects and you can download them @ npmjs.com
- Command Line Utility: It enables you to install various node.js packages and manage versions and dependencies of node.js packages.
Node.JS Modules
Node.JS has many modules that represent functionalities that are packaged into single or multiple files.
They will have a unique context and enable users with code reusability for enhancing the ease of usage. They offer three types of modules as follows
- Core Modules
- Local Modules
- Third-Party Modules
Core Modules
The core module bundles will contain minimum functionalities as it is a lightweight framework.
They will be loaded when the node process begins its execution. User has to import the core modules for utilizing them in their code and the following are the important core modules
- http: It consists of classes, methods, and events for creating a Node.JS HTTP server
- url: It contains methods for URL resolution and parsing in Node.JS
- querystring: It has methods for managing with a query string of node.js
- path: It contains methods for managing file paths
- fs: It consists of classes, methods, and events for working with the file I/O.
- util: It contains utility functions for programmers.
The core module can be loaded with the following code
var module = require(‘module_name’);
Local Modules
The local modules are customized modules for creating locally by the user in the application as per the requirement.
They will have various functionalities and features into distinct files and folders that can be distributed in its community easily using NPM.
The local modules should be loaded similar to core modules and the following is the example
Local module.js file creation
var detail = {
name: function (name) {
console.log(‘Name:’ + name);
},
domain: function (domain) {
console.log(‘Domain:’ + domain);
},
}; module.exports = detail;
Here is the way to add a local module into the main application as follows
var myLogModule = require(‘.Local_module.js’);
myLogModule.name(‘Softlogic’);
myLogModule.domain(‘Training’);
It can be executed as follows
node application.js
External or Third-Party Modules
Third-party or external modules can be used by downloading through NPM and they might be developed by other developers for free usage.
Some of the popularly used external modules are gulp, react, mocha, express, and so on.
Loading third-party module
npm install –g <module_name>
Adding the module file in the main application as follows
npm install –save <module_name>
JSON File
The heart of the node.js application is the package.json file as it contains the metadata of the project.
It is very much important to have a better understanding and practice this JSON file in the development of the project with Node.JS.
As the package.json file consists of metadata of the application, it can be categorized as follows
- Identifying the properties of metadata: The properties of metadata like project name, module version of the current update, license, author of the project, and project description.
- Writing to file directly: We can write the necessary information directly into the package.json file and add it to the project.
Basics of Node.JS
Node.JS is the popular JavaScript framework and it uses the syntax of JavaScript. Some of the fundamentals are as follows
Data Types
Node.JS has various data types like many other programming languages and they will be categorized as primitive and non-primitive data types.
Primitive data types are string, number, Boolean, Null, and Undefined. Some of the non-primitive data types are object, date, array, and so on.
Variables
Variables are the units that store values that are changed based on the information of a program.
We need to make use of reserved keyword var for creating variables in Node.JS. It is not mandatory to assign a data type as the compiler picks it automatically.
Syntax: var varName = value;
Operators
Node.JS supports operators like arithmetic (+,-, *,/, %, ++, –), assignment (=, +=, -=, *=, %=, /=), conditional (=?) comparison (==, ===, !=, !==, >=, >, <, <=), logical (&&, ||, !), and bitwise (&, |, ^, ~, <<, >>, >>>).
Functions
The function is a pre-written block of code with a name that can be used to perform a particular task repeatedly.
It will be called to our program using a keyword function. Generally, it has two steps and they are function definition and function invoking.
Check out the following syntax for creating and invoking a function.
Example
function display_Name(EmpName, EmpRoll) //function definition
{
alert(“Welcome” + EmpName + “ “ + EmpRoll);
}
Display_Name(“John”, “The Manager”); //Function Invoking
Objects
It is a non-primitive data type in Node.JS that can represent multiple values of properties and methods.
Objects are standalone properties as there is no concept of class and they can be created in the following two ways.
- By Using Object Literal
- By Using Object Constructor
Example
var employee = {
EmpName: “John”, //properties
EmpRoll: “The Manager”,
EmpAge: 35,
EmpSalary = 60000,
getEmpName: function() //method
{
return this.EmpName + ‘ ‘ +this.EmpRoll
}
};
File System
Node.JS will make use of the fs module to access the physical file system for managing all asynchronous and synchronous file I/O operations.
It will be imported as below
var fs = require(‘fs’);
Reading Files in Node.JS
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(8000);
Creating Files
We can use appendFile(), open(), writeFile() for creating files in Node.JS
Update Files
Files can be updated using fs.appendFile() and fs.writeFile() methods
Deleting Files
We can use fs.unlink() for deleting files in Node.JS
Rename Files
Files will be renamed using fs.rename() method
Events
As Node.JS is event-driven, it supports concurrency by making use of events and callbacks.
The async function calls support node.js for maintaining concurrency for the entire application.
There will be the main loop that waits and listens for events in node.js and once it is completed, it initiates a callback function immediately.
Binding Event to an Event Listener
var my_Events = require(‘events’) //Importing events module
var my_EvtEmitter = new my_Events.EventEmitter(); //creating an event emitter object
Binding Event Handler to an Event
my_EvtEmitter.on(‘eventName’, eventHandler);
Firing an Event
my_EvtEmitter.emit(‘eventName’); //Firing an event
Example for 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);
HTTP Module
As Node.JS is used widely for creating server-side applications, we can use the HTTP module for creating web servers for responding to client requests.
It provides modules like HTTP requests for facilitating node.js to process the server requests.
HTTP module can be added to our node.js application as follows
var http = require (‘http’);
Example for creating a web server in Node.JS using the HTTP module
var http = require (‘http’); // calling http library
var url = require(‘url’);
var server = http.createServer(function(req,res) //creating a server
{
res.writeHead(200, (‘Content-Type’, ‘text/html’)); //setting content header
var a = url.parse(req.url, true).query;
var t = a.year + “ “ + a.month;
res.end(t); //sending string to response
};
server.listen(8082); //assigning 8082 server for port listening
Express.JS
Express.JS is the node.js framework for facilitating the flow of data between servers and routes in server-side application development.
It provides a lot of features needed for web and mobile application development using node.js.
It is used to develop middleware module of the node.js known as connect. It utilizes an HTTP module to communicate with node.js.
Thus, the interaction between a middleware module and node.js integration becomes easy through express.js.
Following are the advantages of Express.JS
- Faster web application development
- Helps in developing single-page, multi-page, and hybrid types of mobile and web application development
- Two various template engines such as Jade and EJS
- Supported by MVC (Model-View-Controller) architecture
- Easy integration with databases like MongoDB, MySQL, and Redis
- Supports Error Handling Middleware
- Easy configuration and customization for the application development
Thus, the MEAN Stack is structured with MongoDB, Express.JS, Angular.JS, and Node.JS for developing dynamic websites and web applications easily and faster.
Express.JS can be used as follows
npm install -g express
Node.JS Tutorial for step-by-step application development along with Express.JS implementation
Prerequisites for developing applications using node.js and express.js
- package.json
- script.js
- views such as index.jade, login.jade, secure.jade, unauthorized.jade, and welcome.jade
- lib as routes.js
package.json
{
“author”: “Softlogic”,
“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”: {}
}
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);
Views: 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
Views: Login.JS
!!! 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}
Views: 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 Node.JS Tutorial By Softlogic!
Views: secure.jade
!!! 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
Views: unauthorized.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 Unauthorized
p You’re unauthorized to view this page.
p Please <a href=”/login”>login</a> to continue
Lib: route.js
The route.js is used to 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(‘/’);
});
};
Conclusion
We have provided here the fundamental node.js tutorial with example for hoping it is useful for beginners.
We offer the Best Node.JS Training in Chennai at Softlogic Systems with hands-on exposure.
Begin your career in web development by learning in our Node.JS Training Institute.