Backend Development
With Node.JS
Instructor – Satya Priya Arya
UNIT 1
Introduction to Node.js
Frontend v/s Backend v/s Database
The front end is the part of the website users
can see and interact with such as the
graphical user interface (GUI) and the
command line including the design,
navigating menus, texts, images, videos, etc.
Examples – HTML, CSS, Java-Script, jQuery,
React
The backend, on the contrary, is the part of
the website users cannot see and interact
with.
Example – C, C++, Java, Node.JS, C#
The database used to store permanent
What is Node.JS
Node.js is an open source server environment
Node.js runs on various platforms (Windows,
Linux, Unix, Mac OS X, etc.)
Node.js uses JavaScript on the server
History of Node.js
Before 2009, web browsers used JavaScript.
JS was invented in the 1990 as a scripting
language for adding dynamic features to a
web page from an HTML file.
On the other hand, Ryan Dahl created a
runtime environment for JavaScript to
operate outside of web browsers in 2009.
npm, a package manager for the Node.js
environment, was released in January 2010.
Current version is 19.4.0 (LTS version is
18.13.0)
Why Node.js – part 1/2
Typical backend application works
Receive Request
Process Request
Send Response
Wait for next request
How Node.JS work
Receive Request
Ready to handle next request
Send response when previous request
completed
Why Node.js – part 2/2
Node.js eliminates the waiting, and simply
continues with the next request.
Node.js is
single-threaded,
non-blocking,
asynchronous programming
Node.js Architecture – part 1/3
Requests: Depending on the actions that a user needs to perform,
the requests to the server can be either blocking (complex) or non-
blocking (simple).
Node.js Server: The Node.js server accepts user requests,
processes them, and returns results to the users.
Event Queue: The main use of Event Queue is to store the incoming
client requests and pass them sequentially to the Event Loop.
Thread Pool: The Thread pool in a Node.js server contains the
threads that are available for performing operations required to
process requests.
Event Loop: Event Loop receives requests from the Event Queue
and sends out the responses to the clients.
External Resources: In order to handle blocking client requests,
external resources are used. They can be of any type ( computation,
storage, etc).
Node.js Architecture – part 2/3
Node.js Architecture – part 3/3
Users send requests (blocking or non-blocking) to the server
for performing operations.
The requests enter the Event Queue first at the server-side.
The Event queue passes the requests sequentially to the event
loop. The event loop checks the nature of the request
(blocking or non-blocking).
Event Loop processes the non-blocking requests which do not
require external resources and returns the responses to the
corresponding clients
For blocking requests, a single thread is assigned to the
process for completing the task by using external resources.
After the completion of the operation, the request is
redirected to the Event Loop which delivers the response back
to the client.
Working and Features
Installation and Setup
Install Node.JS from
https://nodejs.org/
Install Visual Studio Code from
https://code.visualstudio.com/download
REPL Environment
REPL is a computer environment like a Windows
console or Unix/Linux shell where a command is
entered and the system responds with an output
in an interactive mode. Node.js or Node comes
bundled with a REPL environment
Read − Reads user's input, parses the input into
JavaScript data-structure, and stores in memory.
Eval − Takes and evaluates the data structure.
Print − Prints the result.
Loop − Loops the above command until the user
presses ctrl-c twice.
REPL Environment Samples
$ node
>1+2
3
$ node
> console.log("Hello World")
Hello World
$ node
> var x = 0
undefined
> do {
... x++;
... console.log("x: " + x);
... }
while ( x < 5 );
x: 1
x: 2
x: 3
x: 4
x: 5 undefined
>
REPL Commands
ctrl + c − terminate the current command.
ctrl + c twice − terminate the Node REPL.
ctrl + d − terminate the Node REPL.
Up/Down Keys − see command history and modify
previous commands.
tab Keys − list of current commands.
.help − list of all commands.
.break − exit from multiline expression.
.clear − exit from multiline expression.
.save filename − save the current Node REPL session to a
file.
.load filename − load file content in current Node REPL
session.
Components of Node.js
Node contains many components to develop,
test and deploy applications. Main
components are
Node CLI
NPM
Package.json
Modules
Third party modules (example mongodb)
Core modules (example update)
Development tools and framework
UNIT 2
Node.js Modules
Modules
Modules is same as libraries.
functionality you want to include in your
application.
Module in Node.js is a simple or complex
functionality organized in single or multiple
JavaScript files which can be reused
throughout the Node.js application
Few build-in modules are fs, http, net, os,
path, querystring, stream, url, util
We can create our own modules too.
First Program
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end('Hello World!');
}).listen(8080);
Save file as hello.js
Run “node hello.js” from terminal
Open browser and open http://localhost:8080/
Modify res.end('Hello World!'); to res.write(req.url)
and try with http://localhost:8080/Hello/
Module Exports
The module.exports in Node.js is used to
export any literal, function or object as a
module. It is used to include JavaScript file
into node.js applications.
module.exports = literal | function | object
Here the assigned value (literal | function |
object) is directly exposed as a module and
can be used directly.
module.exports.variable = literal | function |
object
Here the assigned value (literal | function |
object) is indirectly exposed as a module and
Exports Literals
module.exports = “Hello world example";
save in app.js
const demo = require("./app");
console.log(demo);
save in index.js
Exports Objects
module.exports = {
name: ‘Learn node js',
website: 'https://nodejs.org'
}
const demo = require('./app');
console.log(demo.name);
console.log(demo.website);
Exports Functions
module.exports = function (a, b) {
console.log(a + b);
}
const sum = require('./app');
sum(2, 5);
Exports Functions as Class
module.exports = function () {
this.name = ‘Hello Demo';
this.website = 'https://nodjs.org';
this.info = () => {
console.log(`Company name - ${this.name}`);
console.log(`Website - ${this.website}`);
}
}
const Company = require('./app');
const firstCompany = new Company();
firstCompany.info();
Exports Multiple Functions
Store many related functions in one js file
function add(x, y) { return x + y; }
function subtract…
function mutliply …
function divide…
…
Module.exports = { add, subtract, multiply, … }
Use whichever is required
const f = require('./func');
const result = f.add(10, 5);
Loading Module from separate folder
Navigate to parent or child folder and locate
location of module.
Examples:
const index =
require('./models/folder/path/index.js');
const module =
require('../../controllers/index.js');
File System Module
File System module allows you to work with
the file system on your computer.
var fs = require('fs');
Common use for the File System module:
Create
Read
Update
Rename
Delete
Synchronous v/s Asynchronous
Synchronous also called blocking functions
It waits for operation to complete, and only
after that, it executes the next operation
Asynchronous also called non-blocking
functions
It never waits for each operation to complete,
rather it executes all operations in the first go
itself
Most asynchronous methods has
corresponding synchronous method and
suffixed as “Sync”
Read
var fs = require("fs");
// Asynchronous read
fs.readFile('input.txt', function (err, data) {
if (err) {
return console.error(err);
}
console.log("Asynchronous read: " + data.toString());
});
// Synchronous read
var data = fs.readFileSync('input.txt');
console.log("Synchronous read: " + data.toString());
Observe err if file doesn’t exist
Create, Update, Append
//If the file does not exist, the file will be created
fs.appendFile('mynewfile1.txt', 'Hello content!', function (err) {
if (err) throw err;
console.log('Saved!');
});
//If the file does not exist, an empty file is created
fs.open('mynewfile2.txt', 'w', function (err, file) {
if (err) throw err;
console.log('Saved!');
});
//If the file does not exist, a new file, with text, will be created
fs.writeFile('mynewfile3.txt', 'Hello content!', function (err) {
if (err) throw err;
console.log('Saved!');
});
Other useful operations
exists()
existsSync()
truncate()
renameSync()
unlink()
Events and Event Emitters
Node.js is perfect for event-driven applications.
Every action on a computer is an event. Like when a connection
is made or a file is opened.
Node.JS provides way to create and handle custom events.
The EventEmitter class can be used to create and handle
custom events module.
2 steps:
Listening events: Before emits any event, it must register
functions(callbacks) to listen to the events.
Removing Listener: The eventEmitter.removeListener() takes
two argument event and listener, and removes that listener from
the listeners array that is subscribed to that event.
While eventEmitter.removeAllListeners() removes all the
listener from the array which are subscribed to the mentioned
event.
Handling Events
Emitting events example
// Importing events
var EventEmitter = require('events');
// Initializing event emitter instances
var eventEmitter = new EventEmitter();
// Registering to myEvent
eventEmitter.on('myEvent', (msg) => {
console.log(msg);
});
// Triggering myEvent
eventEmitter.emit('myEvent', "First event");
Handling Events
// Initializing event emitter instances
var eventEmitter = new EventEmitter();
var geek1= (msg) => {
console.log("Message from geek1: " + msg);
};
var geek2 = (msg) => {
console.log("Message from geek2: " + msg);
};
// Registering geek1 and geek2
eventEmitter.on('myEvent', geek1);
eventEmitter.on('myEvent', geek2);
// Removing listener geek1 that was
// registered on the line 13
eventEmitter.removeListener('myEvent', geek1);
// Triggering myEvent
eventEmitter.emit('myEvent', "Event occurred");
// Removing all the listeners to myEvent
eventEmitter.removeAllListeners('myEvent');
// Triggering myEvent
eventEmitter.emit('myEvent', "Event occurred");
In-built modules Operating System
The os module provides information about the computer operating system on which node
running.
var os = require('os');
// return the cpu architecture
console.log("CPU architecture: " + os.arch());
// It returns the amount of free system memory in bytes
console.log("Free memory: " + os.freemem());
// It return total amount of system memory in bytes
console.log("Total memory: " + os.totalmem());
// It returns the list of network interfaces
console.log('List of network Interfaces: ' + os.networkInterfaces());
// It returns the operating systems default directory for temp files.
console.log('OS default directory for temp files : ' + os.tmpdir ());
os module common methods
arch()Returns the operating system CPU architecture
cpus()Returns an array containing information about the computer's
CPUs
freemem()Returns the number of free memory of the system
hostname()Returns the hostname of the operating system
loadavg()Returns an array containing the load averages, (1, 5, and
15 minutes)
platform()Returns information about the operating system's
platform
tmpdir()Returns the operating system's default directory for
temporary files
totalmem()Returns the number of total memory of the system
type()Returns the name of the operating system
uptime()Returns the uptime of the operating system, in seconds
userInfo()Returns information about the current user