Node JS
Node JS
1 2/5/2025
Node.js is a JavaScript runtime
network applications.
coding.
2 2/5/2025
Need of Node.js
Let us look at the below scenarios for understanding
the need for Node.js:
Scenario 1: JavaScript has been the most used language
for creating dynamic web pages. JavaScript has moved
to the server-side too, establishing itself on the web
servers as well.
Node.js also represents the "JavaScript everywhere"
paradigm, by unifying web application development
around a single language, rather than using different
3
languages for server-side and client-side. 2/5/2025
Scenario 2: Consider a scenario where you are trying
4
proposed. This is where Node.js comes in. “ 2/5/2025
Since Node.js uses an event looping mechanism,
5 2/5/2025
Node.js - Benefits
1. Node is popular:
6 2/5/2025
Node is the N in the MEAN stack.
In this stack, Node is used along with
the MongoDB database and Express, which is
a Node framework for back-end application
development.
Angular framework is used for front-end
application development.
Node is the N in the MERN stack as well. Here,
Node is used along with MongoDB database
and Express for back-end application
development.
React is used for front-end application
development in this stack.
7 2/5/2025
3. Very fast: Node applications have better performance
than applications developed using other technologies due to
the JavaScript engine used internally in Node. The
engine converts JavaScript code into machine code
and provides extremely fast execution.
4. Node is powerful: Node uses a non-blocking I/O model
and asynchronous programming paradigm, which helps
in processing requests in a non-blocking way.
5. Data Streaming: Node has a built-in Streams API that
helps in creating applications where data
streaming(reading and writing) is required.
8 2/5/2025
6. Rich Ecosystem: Node.js provides a package manager
called “NPM (Node Package Manager) which is the
world's largest software registry that helps open source
developers to share and use packages” using NPM.
7. Modularity: Node applications can be developed as
modules which helps in dividing the application into a
reusable set of code.
8. Wide client-side and database connectivity: Node.js has
absolutely no dependencies and also goes perfectly with
any possible client-side technologies like Angular, React,
etc., and any database like MySQL or MongoDB.
9 2/5/2025
Organizations using Node.js
Node.js is used in applications developed for a wide range
of domains.
11 2/5/2025
What can we build using Node.js?
1. Complex SPA(Single Page Applications)
2. Real-time applications like Chat rooms
3. Data streaming applications
4. REST APIs (Representational State of Resource (REST)
Application Programming Interface, is an architectural
style for designing networked applications. )
5. Server-side web applications
12 2/5/2025
Features of Node.js
1. V8 engine
As application development in Node uses JavaScript
language, the Node.js platform needs an engine for
executing JavaScript.
The engine used in the platform is V8 which is
an open-source high-performance engine.
It is developed by Google and written in C++.
V8 compiles JavaScript source code into native
machine code.
The performance of the Node.js application is faster
due to this ultra-fast engine used in the platform.
13 2/5/2025
2. Single codebase
15 2/5/2025
Synchronous programming
In Synchronous programming, the code execution
happens synchronously. This allows only one task to
execute at a time.
Suppose, we need to read the content of a file and
then database operation is to be executed.
When the file read operation is started,
the rest of the code in the program gets
blocked until the file reading operation is finished.
Once the file reading is done, then it
continues to execute the remaining code.
This kind of code is considered as blocking code or
synchronous code.
16 2/5/2025
Asynchronous programming
The asynchronous code will get executed without
affecting other code execution.
This allows multiple tasks to happen at the same
time.
Example - reading a file and then database
operation is to be executed.
On asynchronously implementing this, when the file
read operation is started, it will not wait for the
read operation to complete, it will just continue
execution of the rest of the code.
This provides a non-blocking way of executing the
code.
17 This improves system efficiency and throughput. 2/5/2025
In Node.js, asynchronous programming is
implemented using the callback functions.
Callback function: A callback is a function passed as
an argument to another function .
It helps in non-blocking code execution.
setTimeout(( ) => {
console.log("after 20 seconds");
}, 20000);
setTimeout() takes two arguments.
The first argument is the callback function and the
second argument is the delay in milliseconds.
The callback function is called after 20 seconds.
18 2/5/2025
4. Single-threaded event loop model
19 2/5/2025
Single-threaded model with the event loop of Node.js
20 2/5/2025
Single-threaded event loop model processing
steps:
Step 1: Assume 'n' number of clients, send requests to
the webserver to access the web
application concurrently.
Node web server receives those requests and places them
into a queue known as "Event Queue".
The Node web server internally maintains a limited
thread pool to provide service to the client. Let us
assume that 'm' number of threads can be created and
maintained.
Step 2: The Node web server internally has a
component, known as "Event Loop". It uses the indefinite
loop to receive requests and process them. But the Event
loop component uses a "Single Thread" to process the
21 requests. 2/5/2025
Step 3: The event Loop component checks for any
client request that is placed in the Event Queue. If the
requests are present, then it picks up one client request
from the Event Queue and starts processing that
request.
23 2/5/2025
5. Scalability
Scalability - to serve a huge number of incoming
requests concurrently.
scales up automatically to serve those requests
efficiently.
6. I/O bound operations
Node.js can be used to create I/O bound applications
that involve huge input-output operations, such as
creating real-time applications.
Applications like Facebook, online chat applications,
and Twitter are a few examples.
24 2/5/2025
7. Streaming of data
Node.js has a built-in Stream API available, using
which we can stream the data very fast.
Applications like the Twitter stream, video stream,
etc. use this feature.
Media companies like National Public Radio, Direct TV,
HBO makes use of Node.js to stream the data to their
viewers.
8. Modularity
Node.js supports modular JavaScript.
Instead of writing code in a single JavaScript file, the
code can be written in modules which can then be
accessed at multiple places in the application.
This helps in easy maintenance and reusability of the
code.
25 2/5/2025
Where to use Node.js and where not to?
Node.js.
26 2/5/2025
Node.js in the web application stack
Now let us take a look at the position of Node.js in the
27 2/5/2025
28 2/5/2025
How to use Node.js
Download Node.js from the official site.
node -v
29 2/5/2025
The flag -v will display the version of Node.js installed in the
machine.
30 2/5/2025
Highlights:
Demo steps:
32 2/5/2025
Visual Studio Code IDE
You can also open the NodeJS folder, in Visual Studio Code
IDE. To execute the first.js file, open the integrated
terminal and issue the command for executing the file. You
will get the output as shown below:
34 2/5/2025
So, we can now conclude that any JavaScript file which
doesn't contain codes for browser interactions will execute
successfully using the Node platform.
35 2/5/2025
Create web server in Node.js – Demo
Highlights:
Using require() and createServer() method
Running a web server in Node.js
Demosteps:
Step 1: Create a new JavaScript file httpserver.js and include
the HTTP module.
const http = require("http");
Step 2: Use the createServer() method of the HTTP module to
create a web server.
var server = http.createServer((req, res) => {
res.write("Hello World! I have created my first server!");
res.end();
});
server.listen(3000);
36 console.log("Server started... Running on localhost:3000");
2/5/2025
Step 3: Save the file and start the server using
the node command. When the file executes successfully,
we can observe the following output in the console.
What is NPM?
NPM stands for Node Package Manager which is a
collection of all the open-source JavaScript libraries
available in this world. It is the world’s largest software
registry maintained by the Node.js team.
38 2/5/2025
The npm CLI
NPM provides a command-line interface "npm" to work with
the NPM repository, which comes bundled with Node. This
tool can be used to install, update, or uninstall any package
through NPM.
How to get the packages to be installed in our
application?
To install any NPM package use the below code in the
command prompt:
npm install <package_name>[@<version>]
This will create a folder node_modules in the current
directory and put all the packages related files inside it.
Here @version is optional if you don't specify the version,
the latest version of the module will be downloaded.
You can even get tools from NPM
like @angular/cli, typescript (compiler), etc.
There are two modes of installation through NPM
Global
39 Local 2/5/2025
Global installation
If we want to globally install any package or tool add -g to
the command. On installing any package globally, that
package gets added to the PATH so that we can run it
from any location on the computer.
npm install -g <package_name>
Consider the scenario where "express" which is the most
popular framework of Node to be used in our application.
Then it can be installed using NPM as below.
npm install -g express
To install any package that is to be available from
anywhere on the computer, then better to go for global
installation.
40 2/5/2025
Local installation
module.
application.
49 2/5/2025
Node Package Manager
Highlights:
Usage of NPM
Installing a module using NPM
Demo steps:
Step 1: Write the following statement in your terminal in
order to install the express module using npm.
npm install -g express
Step 2: You can observe the following in your integrated
terminal.
51 2/5/2025
Modularizing Node application
In an Enterprise application, it is not possible to have all
the logic written in a single file.
As the complexity of the program increases, it reduces
the readability and maintainability of the application.
In this kind of environment, it is easy to lose track of what
a particular code does or to produce reusable code.
So the application needs to be created in
a modularized fashion.
What is modularization?
Modularization is a software design technique in which
the functionality of a program is separated into
independent modules, such that each module contains
52
the desired functionality. 2/5/2025
Advantages of Modularization
Readability: Modular code highly organizes the program
based on its functionality. This allows the developers to
understand what each piece of code does in the
application.
Easier to debug: When debugging large programs, it is
difficult to detect bugs. If a program is modular, then each
module can be debugged easily by the programmer.
Reusable Code: Modular code allows programmers to
easily reuse code to implement the same functionality in a
different program.
Reliability: Modular code will be easier to read. Hence it
will be easier to debug and maintain the code which
ensures smoother execution with minimum errors.
53 2/5/2025
Node environment provides many built-in modules that
can be used in application development.
We have already seen the usage of the "HTTP" module,
which is a built-in module in Node.js for creating a web
server.
Node.js also provides many other useful modules like fs
module (used for file-related operations), os
module(used for operating system-related functions), net
module( used for socket programming), etc. for server-
side application development.
Let us explore how to modularize an application in
Node.
How to modularize code?
Consider a simple Node.js application with a Javascript
file calculator.js with the below code:
54 2/5/2025
calculator.js
async function add(operator1, operator2)
{
return 'Result: ', operator1 + operator2;
}
async function substract(operator1, operator2)
{
return 'Result: ', operator1 - operator2;
}
async function asyncCall()
{
console.log('calling');
const result = await add(2, 3);
console.log(result);
}
asyncCall();
55 2/5/2025
By default the functions declared in one module are visible
56 2/5/2025
exports.add = async (operator1, operator2) => {
};
};
57 2/5/2025
Importing a module
Let us now understand how to import
the calculator.js file into another file.
Consider another file tester.js, where we need to import
and use the functions in the calculator.js file.
Use require() function and specify the module name to
be imported as shown below:
const myCalculator = require("./Calculator");
The require() function takes the path of the file as a
parameter and returns an exports object. Now in order to
use the methods of calculator.js add the below code in
the tester.js file:
myCalculator.add(10, 30);
58 myCalculator.substract(30, 10); 2/5/2025
On executing the tester.js file, we will get the following
output:
59 2/5/2025
Creating a module in Node
Highlights:
Creating a module
Loading the module
Demosteps:
Step 1: Create a file DBModule.js within the NodeJS
folder created earlier.
exports.authenticateUser = (username, password) => {
if (username === "admin" && password === "admin") {
return "Valid User";
}
else return "Invalid User";
};
60 2/5/2025
Step 2: Modify the file httpserver.js file created earlier as
below.
app.js
const http = require("http");
var dbmodule = require("./DBModule");
var server = http.createServer((request, response) => {
result = dbmodule.authenticateUser("admin", "admin");
response.writeHead(200, { "Content-Type": "text/html" });
response.end("<html><body><h1>" + result +
"</h1></body></html>");
console.log("Request received");});
server.listen(3000);
console.log("Server is running at port 3000");
In the httpserver.js file, we are loading the module "DBModule"
61 and then invoking the function named "authenticateUser()".
2/5/2025
Step 3: Run the httpserver.js using the node command.
62 2/5/2025
Restarting Node Application
Whenever we are working on a Node.js application and we
do any change in code after the application is started, we
will be required to restart the Node process for changes to
reflect.
In order to restart the server and to watch for any code
changes automatically, we can use the Nodemon tool.
Nodemon: is a command-line utility that can be executed
from the terminal.
It watches the application and whenever any change is
detected, it restarts the application.
To install it in the application, run the below command.
npm install nodemon -g
63 2/5/2025
Once the 'nodemon' is installed in the machine, the
nodemon app.js
64 2/5/2025
const http = require("http");
var server = http.createServer((req, res) => {
res.write("Hello World! I have created my first server!");
res.end();
});
server.listen(3000);
console.log("Server started... Running on localhost:3000");
Observe the console on starting the nodemon in a
command prompt window.
65 2/5/2025
Now open the application code and do changes in the code
as below.
const http = require("http");
var server = http.createServer((req, res) => {
console.log("Request URL is " + req.url);
res.write("Hello World! I have created my first server!");
res.end();
});
server.listen(3000);
console.log("Server started... Running on localhost:3000");
66 2/5/2025
Observe the console message in the command prompt.
Nodemon automatically restarted the server on observing
changes in the code.
70 2/5/2025
If the file does not exist, then a new file will be
created with the specified name and content.
Syntax:
77 2/5/2025
Reading data from a file
The fs.readFile() method is used to read the content from
a given file.
Syntax:
fs.readFile(path, encoding, callback);
path: Path where the file with data/content resides, with
respect to the root folder.
encoding: an optional parameter that specifies the type of
encoding to read the file. Possible encodings are 'ascii',
'utf8', and 'base64'. If no encoding is provided, the default
is utf8.
callback: The callback method, that will be executed,
when readFile() function is executed.
78 2/5/2025
Consider the below sample code for reading data from a
file "myData.txt".
const fs = require('fs');
const { promisify } = require('util');
const readFile = promisify(fs.readFile);
(async () => {
try {
const fileData = await readFile('myData.txt', 'utf8');
console.log(fileData);
}
catch (err) {
console.log(err);
}
})();
79 2/5/2025
Demo: Writing data to a file
Highlights:
Usage of fs.writeFile() method
To 'write' data to a file
Step 1: Create a file fileSystem.js and paste the below code in
the file.
const fs = require('fs');
const { promisify } = require('util');
const writeFile = promisify(fs.writeFile);
(async () => {
try {
await writeFile('myData.txt', `Hey @ ${new Date()}`);
console.log('File created successfully with promisify and
async/await!');
}
catch (err) { console.log(err); }
})();
80 2/5/2025
Step 2: Run the above code using node command 'node
fileSystem.js' to see the output.
82 2/5/2025
Demo - Appending data to a file
Highlights:
Demosteps:
Step 1: Create a file log.js and paste the below code in the file.
the file does not exist, then it creates a new file with the
content, else it appends the given content to the existing file.
83 2/5/2025
const fs = require('fs');
const { promisify } = require('util');
const appendFile = promisify(fs.appendFile);
(async () => {
try {
await appendFile('myLogger.txt', `Request received @
${Date()} \n`);
console.log('File content appended successfully');
}
catch (err) { console.log(err);
}
})();
84 2/5/2025
Step 2: Run the above code using node command 'node
log.js' to see the output.
85 2/5/2025
Demo - Reading data from a file
Highlights:
Usage of fs.readFile() method to read the content of file.
Demosteps:
Step 1: Create a JavaScript file 'fileSystem.js' and add the
below code:
const fs = require('fs');
const { promisify } = require('util');
const readFile = promisify(fs.readFile);
(async () => {
try {
const fileData = await readFile('demo.txt', 'utf8');
console.log(fileData);
}
catch (err) { console.log(err); }
})();
86 2/5/2025
Step 2: Create a file demo.txt and add the following text.
Node.js is an open-source JavaScript run time
environment which helps the developers to build fast,
scalable network applications. Express is a very popular
framework for Node.js, which simplifies the Node
application development.
Step 3: Run the file 'fileSystem.js' and observe the output
in the console.
87 2/5/2025
THANK YOU
88 2/5/2025