Node Js
Node Js
INTRODUCTION
What is Node.JS?
•Single Process Model: A Node.js application operates within a single process, avoiding the
need to create a new thread for every request.
•Asynchronous I/O: Node.js provides a set of asynchronous I/O primitives in its standard
library. These primitives prevent JavaScript code from blocking, making non-blocking behavior the
norm.
•JavaScript Everywhere: Frontend developers familiar with JavaScript can seamlessly transition to
writing server-side code using Node.js.
Why Node.JS?
Node.js is used to build back-end services like APIs like Web App, Mobile App or Web
Server. A Web Server will open a file on the server and return the content to the client.
It’s used in production by large companies such as Paypal, Uber, Netflix, Walmart,
and so on.
•It allows you to run JavaScript code outside the browser, making it ideal
for building scalable server-side and networking applications.
•JavaScript was earlier mainly used for frontend development. With Node
JS (Introduced in 2009), JavaScript became a backend language as well.
•Non-blocking, event-driven architecture for high performance.
•Supports the creation of REST APIs, real-time applications,
and microservices.
•Comes with a rich library of modules through npm (Node Package
Manager).
Reasons to Choose Node.js
•Easy to Get Started: Node.js is beginner-friendly and ideal for prototyping and agile
development.
•Scalability: It scales both horizontally and vertically.
•Real-Time Web Apps: Node.js excels in real-time synchronization.
•Fast Suite: It handles operations quickly (e.g., database access, network connections).
•Unified Language: JavaScript everywhere—frontend and backend.
•Rich Ecosystem: Node.js boasts a large open-source library and supports asynchronous, non-
blocking programming.
2.Express.js: Express is a popular web application framework for Node.js. It simplifies routing,
middleware handling, and request/response management. Many developers choose Express for
building APIs, web servers, and single-page applications.
4.Mongoose: If you’re working with MongoDB (a NoSQL database), Mongoose provides an elegant
way to model your data and interact with the database. It offers schema validation, middleware,
and query building.
Features:
Removed:
• Display Web Pages: Turns HTML code into what you see on screen.
• User Clicks: helps you interact with the web pages.
• Updates Content: Allows changes to page using Java Script.
• Loads Files: Gets HTML, images etc. from the server.
JavaScript on Server:
• DataBase Management: Stores, retrieves and manage data efficiently through operations like
CRUD(create, read, update, delete)
• Authentication: verifies user identities to control access to system
• Authorization: permissions and access control.
• Input Validation: Checks incoming data for correctness, completeness and security to prevent malicious
data entry and errors.
• Session Management: Tracks user activity across various requests to maintain state and manage user-
specific settings.
• API management: provides and handles interfaces for applications to interact, ensuring smooth data
exchange and integration.
• Error Handling: manages and respond to errors effectively to maintain system stability and provides useful
error messages.
• Security measures: Implement protocols to protect data from unauthorised access and attacks, such as
SQL injection and cross-site scripting(XSS).
• Data Encryption: secures sensitive information.
Node.js REPL
• The term REPL stands for Read Eval Print and Loop.
• It specifies a computer environment like a window console or a Unix/Linux shell where you can enter the
commands and the system responds with an output in an interactive mode.
• Each part of the REPL environment has a specific work.
Read: It reads user's input; parse the input into JavaScript data-structure and stores in memory.
Eval: It takes and evaluates the data structure.
Print: It prints the result.
Loop: It loops the above command until user press ctrl-c twice.
How to start REPL: You can start REPL by simply running "node" on the command prompt. See
this:
Node.js Simple expressions
Using variable
• Variables are used to store values and print later.
• If you don't use var keyword then value is stored in the variable and printed whereas
if var keyword is used then value is stored but not printed.
• You can print variables using console.log().
Node.js Multiline expressions
Node REPL supports multiline expressions like JavaScript. See the following do-while loop example:
var x = 0
undefined
> do {
x++;
console.log("x: " + x);
} while ( x < 10 );
Node.js Underscore Variable
Commands Description
•It provides online repositories for node.js packages/modules which are searchable on
search.nodejs.org
•It also provides command line utility to install Node.js packages, do version management and
dependency management of Node.js packages.
Open the Node.js command prompt and execute the following command:
Console.log(request); });
Console.log(request);
});
Node.js Modules
• Modules in Node.js are blocks of encapsulated code that can be reused throughout your
application.
• These modules can include functions, objects, and variables that are exported from the code
files.
• Modules in Node.js are like JavaScript libraries — a set of related functions that you can include
in your application.
At its core, a Node.js module is an object that contains the following key properties:
•exports: The object that a module can export for use in other modules.
• Core Modules
• Local Modules
• Third-party modules
Core Modules
Node.js has many built-in modules that are part of the platform and come with Node.js installation. These
modules can be loaded into the program by using the required function.
Syntax:
const module = require('module_name');
};
Third-party modules
Third-party modules are modules that are available online using the Node Package
Manager(NPM). These modules can be installed in the project folder or globally. Some of the
popular third-party modules are Mongoose, Express, Angular, and React.
Example:
•npm install express
•npm install mongoose
•npm install -g @angular/cli
•Maintainability: By breaking down the code into smaller, focused modules, it’s
easier to manage, update, and debug applications as they grow in complexity.
• It is primarily used to manage packages or modules—these are pre-built pieces of code that
extend the functionality of your Node.js application.
• The NPM registry hosts millions of free packages that you can download and use in your
project.
• NPM is installed automatically when you install Node.js, so you don’t need to set it up
manually.
Verify the Installation
After installation, verify Node.js and NPM are installed by running the following commands in your
terminal:
node -v
npm -v
Software Package Manager:
Download a Package
Using a Package
Include the "upper-case" package the same way you include any other module:
var uc = require('upper-case');
var http = require('http');
Create a Node.js file that will convert var uc = require('upper-case');
the output "Hello World!" into upper- http.createServer(function (req, res) {
case letters: res.writeHead(200, {'Content-
Type': 'text/html'});
res.write(uc.upperCase("Hello World!"));
res.end();
}).listen(8080);
REVISION of npm
• Node Package Manager (NPM) is a command line tool that installs, updates or uninstalls Node.js packages in your
application.
• The node community around the world creates useful modules and publishes them as packages in this repository.
• It has now become a popular package manager for other open-source JavaScript frameworks like AngularJS, jQuery,
Gulp, Bower etc.
• Official website: https://www.npmjs.com
• NPM is included with Node.js installation. After you install Node.js, verify NPM installation by writing the following
command in terminal or command prompt.
• C:\> npm -v
• If you have an older version of NPM then you can update it to the latest version using the following command.
• Npm install npm –g
In the global mode, NPM performs operations which affect all the Node.js applications on the
computer
In the local mode, NPM performs operations for the particular local directory which affects an
application in that directory only.
Use --save at the end of the install command to add dependency entry into package.json of your
application.
For example, the following command will install ExpressJS in your application and also adds
dependency entry into the package.json.
var fs = require('fs');
var rs = fs.createReadStream('./demofile.txt');
rs.on('open', function () {
console.log('The file is open');
});
Using Modules in Node.js File:
res.writeHead(200,{‘content-type’:’text/html’});
res.end(‘Hello World!’);
}).listen(8080);
• The response.write() method is an inbuilt Application program Interface of the ‘http’ module
which sends a chunk of the response body that is omitted when the request is a HEAD request.
Using the built-in HTTP Module
The HTTP module of Node.js allows data transfer using HyperText Transfer Protocol.
res.end();
}).listen(8080);
HTTP message headers are represented by an object
like this:
{ "content-length": "123",
"content-type": "text/plain",
"connection": "keep-alive",
"host": "example.com",
"accept": "*/*" }
res.writeHead(200,{‘content-type’:’text/html’});
Res.write(request.url); //to retrieve the url value of the clients request
res.end(‘Hello World!’);
}).listen(8080);
Binary Data: Binary data is data that can only have two possible values, usually represented as 0 and 1
1 01 001 0001 1
10 010 0010 2
11 011 0011 3
100 0100 4
The memory of a Computer is any physical device that is capable of storing information whether
it is large or small and stores it temporarily or permanently. For example, Random Access Memory
(RAM), is a type of volatile memory that stores information for a short time, on an integrated
circuit used by the Operating System.
Memory can be either volatile or non-volatile. Volatile memory is a type of memory that loses its
contents when the computer or hardware device is switched off. RAM is an example of a volatile
memory i.e. if your computer gets rebooted while working on a program, you lose all the unsaved
data. Non-volatile memory is a memory that keeps its contents saved even in the case of power
loss. EPROM((Erasable Programmable ROM) is an example of non-volatile memory.
Units of Memory
A computer processor is made up of multiple decisive circuits, each one of which may be either
OFF or ON. These two states in terms of memory are represented by a 0 or 1. To count higher
than 1, such bits (Binary Digits) are suspended together. A group of eight bits is known as a Byte.
1 Byte can represent numbers between zero (00000000) and 255 (11111111), or 28 = 256 distinct
positions.
In practice, memory is measured in Kilobytes (KB) or Megabytes (MB). A Kilobyte is not exactly,
as one might expect, 1000 Bytes. Rather, the correct amount is 210 i.e. 1024 bytes.
Types of File Sizes
•Bit
•Nibble
•Byte
•Kilo Byte
•Mega Byte
•Giga Byte
•Tera Byte
•Peta Byte
•EXA Byte
•Zetta Byte
•Yotta Byte
Data Transfer Speeds
File transfer speed or data transfer speed refers to the speed at which data is
transmitted from one source to another. Typically measured in bits or bytes per
second. Some of the file transfer speeds are:
•Bits per Second(bps): It is the smallest unit of data transfer speed or file
transfer speed.
•Bytes per Second(Bps): 1Bps = 8bps. 1 byte=8 bits.
•Kilobyte per second (KBps): 1kBps= 1024 Bps. 1kB = 1024 Bytes.
•Megabyte per second (MBps): 1MBps= 1024 KBps. 1MB = 1024 Kilobytes.
•Gigabyte per Second (GBps): 1GBps= 1024 MBps. 1 GB= 1024 Megabytes.
•Terabyte per Second (TBps): 1TBps= 1024 GBps. 1 TB= 1024 Gigabytes.
•Petabyte per Second (PBps): 1 PBps = 1024 TBps. (1 PB = 1024 Terabytes).
The fastest data transfer speed achieved is 1.84 petabits per second (Pbps) on October 2022.
Which is 14720000000 Megabits per second(mbps).
What is Character Encoding System?
computers do not understand the English alphabet, numbers except 0 and 1, or text symbols.
We use encoding to convert these. So, encoding is the method or process of converting a series
of characters, i.e, letters, numbers, punctuation, and symbols into a special or unique format for
transmission or storage in computers.
a 97 A 65
b 98 B 66
c 99 C 67
d 100 D 68
e 101 E 69
f 102 F 70
g 103 G 71
Node.js as a File Server
The Node.js file system module allows you to work with the file system on your
computer.
Node.js gives the functionality of file I/O by providing wrappers around the standard
POSIX functions. All file system operations can have synchronous and asynchronous
forms depending upon user requirements.
To include the File System module, use the require() method:
var fs = require('fs’);
Common use for the File System module:
•Read files
•Create files
•Update files
•Delete files
•Rename files
Key Features
•Error Handling: Includes robust error handling to manage issues such as file not found or
permission errors.
Synchronous approach:
They are called blocking functions as it waits for each operation to complete, only after that,
it executes the next operation.
Asynchronous approach:
They are called non-blocking functions as it never waits for each operation to complete,
rather it executes all operations in the first go itself. The result of each operation will be
handled once the result is available
Reading a File
The fs.read() method is used to read the file specified by fd. This method reads the entire file
into the buffer.
Syntax:
fs.read(fd, buffer, offset, length, position, callback)
Parameters:
•fd: This is the file descriptor returned by fs.open() method.
•buffer: This is the buffer that the data will be written to.
•offset: This is the offset in the buffer to start writing at.
•length: This is an integer specifying the number of bytes to read.
•position: This is an integer specifying where to begin reading from in the file. If the position
is null, data will be read from the current file position.
•callback: It is a callback function that is called after reading of the file. It takes two
parameters:
•err: If any error occurs.
•data: Contents of the file.
Read Files
The fs.readFile() method is used to read files on your computer.
Assume we have the following HTML file (located in the same folder as Node.js):
Demo.html
<html>
<body> Create a Node.js file that reads the HTML file, and return the
<h1>My Header</h1> content:
<p>My paragraph.</p>
</body> var http = require('http');
</html> var fs = require('fs');
http.createServer(function (req, res) {
fs.readFile('demofile1.html', function(err,
data) {
res.writeHead(200,
{'Content-Type': 'text/html'});
res.write(data);
return res.end();
});
}).listen(8080);
The fs.appendFile() method appends specified content to a file. If the file does not exist, the file will be created:
Parameters:
•filepath: It is a String that specifies the file path.
•data: It is mandatory and it contains the data that you append to the file.
•options: It is an optional parameter that specifies the encoding/mode/flag.
•Callback: Function is mandatory and is called when appending data to file is
completed.
Open a File
The fs.open() method is used to create, read, or write a file. The fs.readFile()
method is only for reading the file and fs.writeFile() method is only for writing to
the file, whereas fs.open() method does several operations on a file. First, we
need to load the fs class which is a module to access the physical file system.
Syntax:
fs.open(path, flags, mode, callback)
Parameters:
•path: It holds the name of the file to read or the entire path if stored at other
locations.
•flags: Flags indicate the behavior of the file to be opened. All possible values
are ( r, r+, rs, rs+, w, wx, w+, wx+, a, ax, a+, ax+).
•mode: Sets the mode of file i.e. r-read, w-write, r+ -readwrite. It sets to default
as readwrite.
•err: If any error occurs.
•data: Contents of the file. It is called after the open operation is executed.
The fs.open() method takes a "flag" as the second argument, if the flag is "w" for "writing",
the specified file is opened for writing. If the file does not exist, an empty file is created:
var fs = require('fs');
Syntax:
fs.writeFile(path, data, options, callback)
Parameters:
•path: It is a string, Buffer, URL, or file description integer that denotes the path of the file where
it has to be written. Using a file descriptor will make it behave similarly to fs.write() method.
•data: It is a string, Buffer, TypedArray, or DataView that will be written to the file.
•options: It is a string or object that can be used to specify optional parameters that will affect
the output. It has three optional parameters:
•encoding: It is a string value that specifies the encoding of the file. The default value is
‘utf8’.
•mode: It is an integer value that specifies the file mode. The default value is 0o666.
•flag: It is a string value that specifies the flag used while writing to the file. The default
value is ‘w’.
•callback: It is the function that would be called when the method is executed.
•err: It is an error that would be thrown if the operation fails.
The fs.writeFile() method replaces the specified file and content if it exists. If the
file does not exist, a new file, containing the specified content, will be created:
var fs = require('fs');
•fs.appendFile()
•fs.writeFile()
The fs.appendFile() method appends the specified content at the end of the specified file:
var fs = require('fs');
Syntax:
fs.close(fd, callback)
Parameters:
• fd: It is an integer that denotes the file descriptor of the file for which to be closed.
• callback: It is a function that would be called when the method is executed.
•err: It is an error that would be thrown if the method fails.
if (err) {
console.log(err);
}
console.log("File closed successfully."); });
Delete a File
The fs.unlink() method is used to remove a file or symbolic link from the filesystem.
This function does not work on directories; therefore it is recommended to use
fs.rmdir() to remove a directory.
Syntax:
fs.unlink(path, callback)
Parameters:
• path: It is a string, Buffer or URL which represents the file or symbolic link which
has to be removed.
• callback: It is a function that would be called when the method is executed.
•err: It is an error that would be thrown if the method fails.
Delete Files
To delete a file with the File System module, use the fs.unlink() method.
The fs.unlink() method deletes the specified file:
Delete "mynewfile2.txt":
var fs = require('fs');
var fs = require('fs');
fs.access(path[, mode], callback) Tests a user's permissions for the specified file.
fs.appendFile(file, data[, options], callback) Appends new content to the existing file.
Node.js fs.writeFileSync() Method
The fs.writeFileSync() method is a synchronous method. It creates a new file if the specified file
does not exist. Also, the ‘readline-sync’ module is used to enable user input at runtime.
The ‘fs’ module of Node.js implements the File I/O operation. The fs module methods can be synchronous as well
as asynchronous. The Asynchronous function has a callback function as the last parameter which indicates the
completion of the asynchronous function. Node.js developers prefer asynchronous methods over synchronous
methods as asynchronous methods never block a program during its execution, whereas the latter does.
Syntax:
fs.writeFileSync( file, data, options )
•file: It is a string, Buffer, URL, or file description integer that denotes the path of the file where
it has to be written. Using a file descriptor will make it behave similarly to the fs.write() method.
•data: It is a string, Buffer, TypedArray, or DataView that will be written to the file.
•options: It is a string or object that can be used to specify optional parameters that will affect
the output. It has three optional parameters:
• encoding: It is a string that specifies the encoding of the file. The default value is ‘utf8’.
• mode: It is an integer that specifies the file mode. The default value is 0o666.
• flag: It is a string that specifies the flag used while writing to the file. The default value is
‘w’.
var fs = require('fs');
var fs = require('fs');
fs.writeFile('mynewfile3.txt', 'Hello
content!', function (err) {
if (err) throw err;
console.log('Saved!');
});
console.log(‘File Created Successfully’);
What is fs.readFileSync() ?
The fs.readFileSync Method is used to read the file’s content synchronously and process the files at
initialization.
Syntax:
fs.readFileSync( path, options )
•path: It takes the relative path of the text file. The path can be of URL type. The file can
also be a file descriptor. If both the files are in the same folder just give the filename in
quotes.
•options: It is an optional parameter that contains the encoding and flag, the encoding
contains data specification. Its default value is null which returns the raw buffer and the
flag contains an indication of operations in the file. Its default value is ‘r’.
const fs = require('fs’);
console.log(data);
The order of file reading in Node.js is influenced by the asynchronous nature of `fs.readFile()`
and the synchronous nature of `fs.readFileSync()`. The event loop determines the execution
order, and using `fs.readFileSync()` can block parallel processes, impacting the observed file
read order.
When to Use fs.readFileSync() vs fs.readFile()
•Use fs.readFileSync() :
•When you are working with small files, such as configuration or startup files,
where blocking the execution won’t impact performance.
•In scenarios where synchronous execution is required, such as in scripts that
run before the event loop starts.
•When working with single-threaded, short-lived programs, like command-line
utilities.
•Use fs.readFile() :
•When performance and scalability are critical, such as in web servers handling
multiple requests.
•For non-blocking, event-driven architectures where I/O operations should not
block the event loop.
•In production environments where multiple file reads can happen concurrently,
and blocking could result in significant performance degradation
Node.js Buffer Module
Buffer in Node is a built-in object used to perform operations on raw binary
data. The buffer class allows us to handle the binary data directly. A buffer is a
temporary storage space for binary data. Buffers are particularly useful when dealing
with I/O operations such as reading from or writing to a file or communicating over a
network.
The Buffer object is a global object in Node.js, and it is not necessary to import it using
the require keyword.
The syntax for creating an empty Buffer of the length 15:
var buf = Buffer.alloc(15);
No Method Description
1 Buffer.alloc(size) It creates a buffer and allocates size to it.
•Fixed-Size: Buffers have a fixed size, meaning their length cannot be altered once they are
created.
•Binary Data: They are designed to handle raw binary data, unlike regular JavaScript strings
that handle text data.
•Efficient Memory Usage: Buffers provide a way to manage memory efficiently, allowing for
the manipulation of binary data without the overhead of converting to and from text.
Use Cases
•File Operations: Reading and writing binary files such as images or audio.
•Network Operations: Sending and receiving data over TCP or HTTP protocols.
•Data Streaming: Handling data from streams such as file streams, network streams, or
process streams.
Using alloc() Method
equals() Method
It compares two buffer objects. Returns true if the object match else returns false .
length Property
Return the length of a buffer object in bytes.
let buff = new Buffer.alloc(5, 'ABCDE’);
console.log(buff.length)
toString() Method
It returns a string form of a buffer object.
toJSON() Method
It returns a JSON form of a buffer object.
In Node.js, buffers can be created using the Buffer class provided by the buffer module. Here are some
common ways to create a buffer:
You can create a buffer from a string by specifying the encoding (default is utf-8).
// <Buffer 48 65 6c 6c 6f 2c 20 57 6f 72 6c 64 21>
To create a buffer of a specific size without initializing it, use the Buffer.allocUnsafe method.
This is faster but might contain old data.
Writing to a Buffer
console.log(buffer.toString('utf-8')); // Hello
You can read data from a buffer by converting it to a string or accessing its individual bytes .
Events in Node.js
var fs = require('fs');
• Every action on a computer is an event.
var rs =
Like when a connection is made or a file is
fs.createReadStream('./demofile.txt’);
opened.
rs.on('open', function () {
• Objects in Node.js can fire events, like the
console.log('The file is open');
readStream object fires events when
});
opening and closing a file:
If you worked with JavaScript in the browser, you know how much of the
interaction of the user is handled through events: mouse clicks, keyboard
button presses, reacting to mouse movements, and so on.
On the backend side, Node.js offers us the option to build a similar system
using the events module.
Events
Module
• Node.js has a built-in module, called "Events",
where you can create-, fire-, and listen for- your var events = require('events’);
own events.
• To include the built-in Events module use var eventEmitter
the require() method. In addition, all event = new events.EventEmitter();
properties and methods are an instance of an This module, in particular, offers
EventEmitter object. To be able to access these the EventEmitter class, which we'll use to handle our
properties and methods, create an EventEmitter
events.
object:
This object exposes, among many others, the on and emit methods.
•emit is used to trigger an event
•on is used to add a callback function that's going to be executed when the event is triggered
For example, let's create a start event, and as a matter of providing a sample, we react to that
by just logging to the console:
eventEmitter.on('start', () =>
{ console.log('started’);
});
When we run: the event handler function is triggered, and we get the console log.
eventEmitter.emit('start');
EventEmitter Class
At the core of the Node.js event system is the EventEmitter class. This class allows objects to
emit named events that can be listened to by other parts of your application. It is included in
the built-in events module.
•Event Registration: You can register listeners for specific events using the on() method.
•Event Emission: Use the emit() method to trigger an event and call all registered listeners
for that event.
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.
// Importing events const EventEmitter = require('events’);
Syntax: // Initializing event emitter instances
eventEmitter.removeListener(event, listener) var eventEmitter = new EventEmitter();
eventEmitter.removeAllListeners([event]) var fun1 = (msg) => {
console.log("Message from fun1: " + msg); };
var fun2 = (msg) => {
console.log("Message from fun2: " + msg); }; // Registering
fun1 and fun2
eventEmitter.on('myEvent', fun1);
eventEmitter.on('myEvent', fun1);
eventEmitter.on('myEvent', fun2); // Removing listener
eventEmitter.removeListener('myEvent', fun1);
// Triggering myEvent
eventEmitter.emit('myEvent', "Event occurred");
// Removing all the listeners to myEvent
eventEmitter.removeAllListeners('myEvent’);
// Triggering myEvent eventEmitter.emit('myEvent', "Event
REVISION
Event Driven Programming is a paradigm in which the flow of the program is determined by events
— such as user actions (mouse clicks, key presses), sensor outputs, or messages from other
programs.
Three key concepts:
•Event Emitter (also known as the Producer / Publisher)
An event emitter emits named events that occurred in the application.
•Event Listener (also known as the Consumer / Subscriber)
Event listener is a function that listens to the particular events.
•Event Handler
A callback function that is tasked to handling the event, triggered by the
Event Listener.
Browser Events
Often in web apps, you create listeners for various DOM events, like mouse clicks, key press or other
types of events.
<button id="submit">Submit</button> <script>
const submitBtn = document.getElementById('submit');
•the end user who clicks the button is the Event
submitBtn.addEventListener('click', (event) => {
Emitter
console.log('Clicked!');
}); •The ‘click’ is an Event that app is Listening to
</script> •And the code that executes afterwards is
an Event Handler
Basic Event Emitter // app.js Passing Data while emitting an
event
const EventEmitter = require('events’);
const myEmitter = new EventEmitter(); const EventEmitter = require('events');
const emitter = new EventEmitter();
// Register an event listener
// listen to events (Event Listener)
myEmitter.on('greet', () => {
console.log('Hello, world!’); emitter.on(‘padhLo', (data) => {
console.log('data :>> ', data);
}); // (Event Handler)
});
// Emit the event
// create an event (Event Emitter)
myEmitter.emit('greet'); emitter.emit(‘padhLo’, ‘you must give
assignments on time… Otherwise your
teacher will gonna screw you!!!');
Once Event Listener:- The once method ensures the listener runs only once.
myEmitter.once('welcome', () => {
1. Event-Driven Architecture
Node.js is built on an event-driven architecture, where actions (like user inputs, file operations, or server requests) trigger
events that execute specific callbacks. This design improves efficiency and responsiveness.
Example: The Node.js http module uses events to handle incoming requests.
const http = require('http’); //Import the http module
const server = http.createServer((req, res) => { // the function inside createServer() is a callback that runs whenever the server receives an
HTTP request
server.listen(3000, () => console.log('Server running on port 3000’)); //starts the server and make it listen on
port 3000
3. Real-Time Applications
2. Non-Blocking Asynchronous Operations
Events are essential for building real-time
Events allow Node.js to execute tasks without waiting for applications like chat apps, stock market
previous tasks to complete, making it fast and efficient. trackers, and multiplayer games. [Imagine multile
Example: File reading using events. users in a chat room]
fs.readFile('example.txt', 'utf8', (err, data) => { const io = require('socket.io')(3000); //initialize web socket server
if (err) throw err; io.on('connection', (socket) => { //listens for new clients
connecting.
// The program does not wait for the file to be read; it console.log('Received:', msg);
continues execution.
io.emit('message', msg);
console.log('Reading file...');
// Broadcast message to all clients
}); });
Error Handling with Events
Events can help in handling errors more efficiently by listening for error events.
});
// Contact Route
app.get('/contact', (req, res) => {
res.send('Contact Page’);
});
WHAT IS EXPRESS.JS?
• Express.js is a minimalist web application framework built
on top of node.js providing a robust set of features and tools
for building web applications and APIs.
• Express.js offers a simple and flexible approach to web
development , allowing developers to define routes, handle
request and responses and manage middleware to perform
various tasks.
• With express.js, developers can easily build APIs , create
dynamic web pages, handle authentication and sessions,
and integrate with databases and other external services.
WHY USE EXPRESS.JS?
• Community and
Support : Node.js and
Express.js have active
communities ,extensive documentation ,
and a wealth of online resources,
making it easy to find help and learn
from others.
FEATURES OF EXPRESS.JS
FAST SERVER-
MIDDLEWARE : ROUTING :
SIDE
It is a request handler , Refers to how an
DEVELOPMENT: which have the access application’s endpoints
With the help of node.js to the application’s (URLs) respond to
features Express can request-response cycle. client requests
save a lot of time .
FEATURES OF EXPRESS.JS
TEMPLATING : DEBBUGING :
Creates a html template files Express makes it easier as it
with less code and render identifies the exact part
HTML pages. where bugs are.
INSTALLATION
• In order to install Express.js we need Node.js
already installed.
• NODE.JS INSTALLATION
https://nodejs.org/en/download/
npm init
npm install –g
• Once you are done with Node.js installation, the next step is to
express
Install
Express.npm install express --save
• Step 1.
•
NPM
• NPM (Node Package Manager) Installation
• NPM is the default package manager for Node.js
that is completely written in Javascript.
• In order to install any module using npm :
Template Engine Support: Express supports template engines like EJS, Pug, or
Handlebars for dynamic HTML rendering. Node.js has no built-in template support.
Error Handling Made Easy: Express has centralized error handling using middleware,
making it easier to manage exceptions. In Node.js, error handling can be complex and
repetitive.
This is how you initialize
Express
Expand Node_module
A URI (Uniform Resource Identifier) is a string of characters used to identify a resource on the internet. It
provides a way to locate and interact with resources such as web pages, images, videos, or other services.
2. Authority: Contains information like the domain name or IP address (e.g., www.example.com)
https://www.example.com/products/item1?id=123#section1
Scheme: https
* Thats why its called Dynamic as it Authority: www.example.com
changes with user Path: /products/item1
Query: ?id=123
Fragment: #section1
const express = require('express');
const app = express();
const port = 3000;
Go to http://localhost:3000.
// About route
app.get('/about', (req, res) => {
res.send('This is a basic Express application example.');
});
// Contact route
app.get('/contact', (req, res) => {
res.send('Contact us at [email protected]');
});
// Start server
app.listen(port, () => {
console.log(`Server is running at http://localhost:${port}`);
});
// User Route with ID using Query Parameter
app.get('/user', (req, res) => {
const userId = req.query.id;// req.query.id extracts the id value from the query
if (userId) { parameters (?id=123).
res.send(`User ID is: ${userId}`);
} else {
res.send('Please provide a user ID using ?id=123');
}
http://localhost:3000/user?id=123 → Output: User ID is:
123
// API with URL Parameter
app.get('/api/user/:username', (req, res) => { //username is route
parameter
const username = req.params.username;
res.json({ message: `Hello, ${username}!` });
}); http://localhost:3000/api/user/Sneha
Useful for accessing dynamic resources like user profiles, orders, or
products.
// API with Query Parameters
app.get('/api/calculate', (req, res) => {
const { num1, num2 } = req.query;
if (!num1 || !num2) {
return res.status(400).json({ error: 'Missing parameters num1 or
num2' });
}
const sum = parseInt(num1) + parseInt(num2);
res.json({ result: sum });
});
Task: Folder Structure
express-app/
├── ExpressProgram/
├── index.html
├── style.css
├── server.js
:) Enjoy
Node.js MySQL
• Node.js can be used in database applications.
• One of the most popular databases is MySQL.
• Install MySQL Driver: npm install mysql
• Create Connection
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
});
Creating a Database
Query a Database
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
con.query(sql, function (err,
result) {
if (err) throw err;
console.log("Result: " +
result);
});
});