unit-II
unit-II
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. Node.js modules are key to organizing your code
in manageable chunks.
What are Modules in Node.js?
Modules in Node.js are like JavaScript libraries — a set of related functions that you can include in your application. Every
Node.js file can be considered a module that can export code for reuse in other parts of the application. This modular approach
allows developers to separate concerns, reuse code, and maintain a clean architecture.
How Node.js Modules Work?
Each module in Node.js is executed within its own module scope. This means variables, functions, and classes defined in one
module are private to that module unless explicitly exported for use by other modules. This behavior avoids global namespace
pollution and improves code maintainability.
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.
• require(): A function that is used to import modules into other modules.
• module: The object that represents the current module.
When a module is loaded, Node.js wraps the module code in a function to provide this module system.
In the above example, the require() function returns an object because the Http module returns its functionality as an object.
The function http.createServer() method will be executed when someone tries to access the computer on port 3000.
The res.writeHead() method is the status code where 200 means it is OK, while the second argument is an object containing the
response headers. The following list contains some of the important core modules in Node.js:
Core Modules Description
http creates an HTTP server in Node.js.
assert set of assertion functions useful for testing.
fs used to handle file system.
path includes methods to deal with file paths.
process provides information and control about the current Node.js process.
os provides information about the operating system.
querystring utility used for parsing and formatting URL query strings.
url module provides utilities for URL resolution and parsing.
2. Local Modules
Unlike built-in and external modules, local modules are created locally in your Node.js application. Let’s create a simple
calculating module that calculates various operations. Create a calc.js file that has the following code:
// Filename: calc.js
exports.add = function (x, y) {
return x + y;
};
exports.sub = function (x, y) {
return x - y;
};
exports.mult = function (x, y) {
return x * y;
};
exports.div = function (x, y) {
return x / y;
};
Since this file provides attributes to the outer world via exports, another file can use its exported functionality using the
require() function.
// Filename: index.js
const calculator = require('./calc');
let x = 50, y = 10;
console.log("Addition of 50 and 10 is "
+ calculator.add(x, y));
console.log("Subtraction of 50 and 10 is "
+ calculator.sub(x, y));
console.log("Multiplication of 50 and 10 is "
+ calculator.mult(x, y));
console.log("Division of 50 and 10 is "
+ calculator.div(x, y));
Step to run this program: Run the index.js file using the following command:
node index.js
Output:
Addition of 50 and 10 is 60
Subtraction of 50 and 10 is 40
Multiplication of 50 and 10 is 500
Division of 50 and 10 is 5
Note: This module also hides functionality that is not needed outside of the module.
3. 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
Example: Installing and Using Express
npm install express
Create a Simple Express Server:
const express = require('express');
const app = express();
const port = 3000;
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`);
});
Run the Server: Use this command to run the node application.
node server.js
When you navigate to http://localhost:3000 in your browser, you should see Hello World!.
module.exports
In Node, the `module.exports` is utilized to expose literals, functions, or objects as modules. This mechanism enables the
inclusion of JavaScript files within Node.js applications. The `module` serves as a reference to the current module, and
`exports` is an object that is made accessible as the module’s public interface.
Syntax:
module.exports = literal | function | object
Note: Here the assigned value (literal | function | object) is directly exposed as a module and can be used directly.
Syntax:
module.exports.variable = literal | function | object
Note: The assigned value (literal | function | object) is indirectly exposed as a module and can be consumed using the variable.
Exporting modules in Node.js is key to organizing large projects.
Below are different ways to export modules:
Example 1: Exporting Literals
Create a file named as app.js and export the literal using module.exports.
module.exports = "GeeksforGeeks";
Create a file named as index.js and import the file app.js to print the exported literal to the console.
const company = require("./app");
console.log(company);
Output:
GeeksforGeeks
Example 2: Exporting Object:
Create a file named as app.js and export the object using module.exports.
module.exports = {
name: 'GeeksforGeeks',
website: 'https://geeksforgeeks.org'
}
Create a file named as index.js and import the file app.js to print the exported object data to the console.
const company = require('./app');
console.log(company.name);
console.log(company.website);
Output:
GeeksforGeeks
https://geeksforgeeks.org
Example 3: Exporting Function
Create a file named as app.js and export the function using module.exports.
module.exports = function (a, b) {
console.log(a + b);
}
Create a file named as index.js and import the file app.js to use the exported function.
const sum = require('./app');
sum(2, 5);
Output:
7
Example 4: Exporting function as a class
Create a file named as app.js. Define a function using this keyword and export the function using module.exports and Create a file
named index.js and import the file app.js to use the exported function as a class.
JavaScriptJavaScript
const Company = require('./app');
const firstCompany = new Company();
firstCompany.info();
Output:
Company name - GeeksforGeeks
Website - https://geeksforgeeks.org
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 binary stream is a collection of large amounts of binary data. Due to their
massive size, binary streams are not sent together. Instead, they are broken into smaller pieces before sending.
When the data processing unit cannot accept any more data streams, excess data is stored in a buffer until the data
processing unit is ready to receive more data.
Syntax:
const buf = Buffer.alloc(10); // Allocates a buffer of 10 bytes.
Generally, Buffer refers to the particular memory location in memory. Buffer and array have some similarities,
but the difference is array can be any type, and it can be resizable. Buffers only deal with binary data, and it can not
be resizable. Each integer in a buffer represents a byte. console.log() function is used to print the Buffer instance.
Buffer Methods:
No Method Description
1 Buffer.alloc(size) It creates a buffer and allocates size to it.
2 Buffer.from(initialization) It initializes the buffer with given data.
3 Buffer.write(data) It writes the data on the buffer.
4 toString() It read data from the buffer and returned it.
5 Buffer.isBuffer(object) It checks whether the object is a buffer or not.
6 Buffer.length It returns the length of the buffer.
7 Buffer.copy(buffer,subsection size) It copies data from one buffer to another.
8 Buffer.slice(start, end=buffer.length) It returns the subsection of data stored in a buffer.
9 Buffer.concat([buffer,buffer]) It concatenates two buffers.
Node.js buffer methods
One cool thing about the Node.js buffer module is that you don’t need to import it into your application before
using its methods. Let’s review some important Node.js buffer methods that you should know.
Buffer.alloc()
The Buffer.alloc() method creates a new buffer of any size. When you use this method, you assign the size of the
buffer in bytes. The expression below creates a buffer with a byte size of 6:
const buf = Buffer.alloc(6);
console.log(buf);
// This will print <Buffer 00 00 00 00 00 00>
Buffer.write()
The Buffer.write() method writes a string to the buffer, which can be useful when you need to stream strings in the
form of buffers. You can write a string to a buffer using the below method:
You can check the length of a buffer object with the Buffer.byteLength() method. The code below demonstrates
how to create a buffer, attach a size to it, and check the size of the buffer you just created:
var buf = Buffer.alloc(6);
//check the length of buffer created
var buffLen = Buffer.byteLength(buf);
//print buffer length
console.log(buffLen);
// This will print <6>
Buffer.compare()
The Buffer.compare() method enables you to compare two buffer objects to check whether they are equal. This
method returns -1, 0, or 1, depending on the result of the comparison.
You can compare buffer objects with the Buffer.compare() method as seen below:
var buf1 = Buffer.from('xyz');
var buf2 = Buffer.from('xyz');
var a = Buffer.compare(buf1, buf2);
//This will return 0
console.log(a);
var buf1 = Buffer.from('x');
var buf2 = Buffer.from('y');
var a = Buffer.compare(buf1, buf2);
//This will return -1
console.log(a);
var buf1 = Buffer.from('y');
var buf2 = Buffer.from('x');
var a = Buffer.compare(buf1, buf2);
//This will return 1
console.log(a);
Buffer.concat()
Just like string concatenation, you can join two or more buffer objects into one object. You can also get the length
of the new object:
var buffer1 = Buffer.from('x');
var buffer2 = Buffer.from('y');
var buffer3 = Buffer.from('z');
var arr = [buffer1, buffer2, buffer3];
/*This will print buffer, !concat [ <Buffer 78>, <Buffer 79>, <Buffer 7a> ]*/
console.log(arr);
//concatenate buffer with Buffer.concat method
var buf = Buffer.concat(arr);
//This will print <Buffer 78 79 7a> concat successful
console.log(buf);
buf.entries()
With buf.entries(), you can return a loop of indexes and bytes from the content of a buffer object, which is used to
know the position and size of buffer contents:
var buf = Buffer.from('xyz');
for (a of buf.entries()) {
/*This will print arrays of indexes and byte of buffer content \\[ 0, 120 \][ 1, 121 \][ 2, 122 ]*/
console.log(a);
}
Buffer.fill()
The Buffer.fill() method enables you to create a buffer, allocate a size, and fill it with a specified value. The
expression below shows how to use the Buffer.fill() method:
const b = Buffer.alloc(10).fill('a');
console.log(b.toString());
// This will print aaaaaaaaaa
Buffer.from()
The buffer.from() method enables you to create a new buffer from any object, like strings, buffer, arrays,
and ArrayBuffer(). All you have to do is specify the object you want to create a buffer from.
The syntax for using this method is
Buffer.from(object[, offsetOrEncoding[,length]]).
Node.js - NPM
NPM − an acronym for Node Package Manager, refers to the Command line utility to install Node.js
packages, perform version management and dependency management of Node.js packages. Node
package managers (npms) are software tools that help developers install, manage, and update third-party
software packages for Node.js. npms are essential for Node development, as they provide a central
repository of packages and tools that can be used to create web applications, server-side applications, and
more. It is the default node package manager for Node JS as it comes with the default node js installations.
It is a command line client that allows the developers to publish or install the packages in the npm registry.
Package Registry:
Npm relies on centralised package registry that contains a vast collection of packages published by
developers worldwide. The packages can be pushed to the registry as public packages or private packages.
The public packages in the registry won’t need authorisation to pull the package whereas the private
packages will need the auth tokens to pull and use the npm package.
Package.json:
It is a metadata file in a Node.js project that serves as the manifest for the project’s dependencies, scripts,
configuration, and other details. It is the heart of every npm-managed projects.
Package-lock.json:
It is similar to the package.json file which will have all the details about the project along with the exact
dependency versions which serves as the snapshot of package.json file.The purpose of package-
lock.json file is to ensure that the same dependencies are installed consistently across different
environments, such as development and production environments.
npm CLI:
The npm Command Line Interface is responsible for providing an interface to interact with the package
manager. It allows the developers to run various commands to manage the dependencies and perform
other tasks related to the project.
• Easy installation: npms make it easy to install third-party packages. With just a few commands,
you can install any package that is available in the npm registry.
• Version management: npms help you to manage the versions of the packages that you use. When
you install a package, npm will automatically create a lock file that specifies the exact version of
the package that you are using. This can help to prevent conflicts and errors when you are working
with multiple developers on the same project.
• Dependency management: npms can help you to manage the dependencies of your projects.
When you install a package, npm will automatically install any dependencies that the package
requires. This can help to ensure that your project has all of the necessary dependencies to run
correctly.
• Community support: npms have large and active communities of users and developers. This can
be a valuable resource for getting help with problems, finding new packages, and staying up-to-
date on the latest developments.
Install Package Locally
There is a simple syntax to install any Node.js module −
npm install <Module Name>
For example, following is the command to install a famous Node.js web framework module called
express −
npm install express
Now you can use this module in your js file as following −
var express = require('express');
The local mode installation of a package refers to the package installation in node_modules directory
lying in the folder where Node application is present. Locally deployed packages are accessible via
require() method. Use --save at the end of the install command to add dependency entry into package.json
of your application.
The package.json file is a JSON file that is used to manage dependencies in Node.js projects. It contains
information about the project, such as its name, version, and dependencies. The package.json file is used
by the npm package manager to install and manage dependencies.
The package.json file is typically located in the root directory of a Node.js project. It can be created by
running the npm init command.
Create a new folder for a new Node.js project, and run pnm init command inside it −
PS D:\nodejs\newnodeapp> npm init
if we install express package into this package locally in this project, use the following command, it also
adds dependency entry into the package.json.
{
"name": "newnodeapp",
"version": "1.0.0",
"description": "Test Node.js App",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [
"test",
"nodejs"
],
"author": "mvl",
"license": "ISC",
"dependencies": {
"express": "^4.18.2"
}
}
The express package code will be placed inside the node_modules subfolder of the package folder.
You can also use -save-dev flag in the npm install command to add the package as DevDepndency.
• --save-dev installs and adds the entry to the package.json file devDependencies
• --no-save installs but does not add the entry to the package.json file dependencies
• --save-optional installs and adds the entry to the package.json file optionalDependencies
• --no-optional will prevent optional dependencies from being installed
Shorthands of the flags can also be used −
• -S: --save
• -D: --save-dev
• -O: --save-optional
Update Package
To update the package installed locally in your Node.js project, open the
command prompt or terminal in your project project folder and write the
following update command.
The following command will update the existing ExpressJS module to the latest
version.
found 0 vulnerabilities
Dependency Resolution:
As we have all the dependencies in the package.json file, and running the
command npm install would not simply download all the dependencies in a random
order. It traverses through the dependency tree to identify all the required
packages along with their respective versions. All the packages in the
node_modules are either primary or secondary dependencies.
Primary Dependency — which is there in a package.json and is supposed to be
used in the project.
Secondary Dependency — which is required by these primary dependencies
So npm handles how the packages should be managed for both the primary and
secondary dependencies to ensure all the packages have the proper files to run and
used in the project.
Adding dependencies to a package.json file
You can add dependencies to a package.json file from the command line or by manually editing
the package.json file.
To add an entry to the "dependencies" attribute of a package.json file, on the command line, run the
following command:
npm install <package-name> [--save-prod]
To add an entry to the "devDependencies" attribute of a package.json file, on the command line, run
the following command:
npm install <package-name> --save-dev
Fs module
The fs (File System) module in Node.js provides an API for interacting with the file system. It allows
you to perform operations such as reading, writing, updating, and deleting files and directories, which are
essential for server-side applications and scripts.
Node.js file system
To handle file operations like creating, reading, deleting, etc., Node.js provides an inbuilt module called FS
(File System). 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 use this File System module, use the require() method:
const fs = require('fs');
Uses:
• Read Files
• Write Files
• Append Files
• Close Files
• Delete Files
Key Features
• Asynchronous and Synchronous Methods: Provides both non-blocking and blocking methods for
various file operations.
• Error Handling: Includes robust error handling to manage issues such as file not found or permission
errors.
• Directory Management: Allows creation, deletion, and listing of directories.
// Asynchronous read
fs.readFile("input.txt", function (err, data) {
if (err) {
return console.error(err);
}
console.log("Asynchronous read: " + data.toString());
});
Output:
Asynchronous read: GeeksforGeeks: A computer science portal
const fs = require("fs");
// Synchronous read
const data = fs.readFileSync('input.txt');
console.log("Synchronous read: " + data.toString());
Output:
Synchronous read: GeeksforGeeks: A computer science portal
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.
Example: Let us create a js file named main.js having the following code to open a
file input.txt for reading and writing.
const fs = require("fs");
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:
o err: If any error occurs.
o data: Contents of the file.
Example: Let us create a js file named main.js having the following code:
const fs = require("fs");
const buf = new Buffer(1024);
Writing to a File
This method will overwrite the file if the file already exists. The fs.writeFile() method is used to
asynchronously write the specified data to a file. By default, the file would be replaced if it exists.
The ‘options’ parameter can be used to modify the functionality of the method.
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:
o encoding: It is a string value that specifies the encoding of the file. The default value
is ‘utf8’.
o mode: It is an integer value that specifies the file mode. The default value is 0o666.
o 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.
o err: It is an error that would be thrown if the operation fails.
Example: Let us create a js file named main.js having the following code:
const fs = require("fs");
Appending to a File
The fs.appendFile() method is used to synchronously append the data to the file.
Syntax:
fs.appendFile(filepath, data, options, callback);
// or
fs.appendFileSync(filepath, data, options);
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.
Example 1: Let us create a js file named main.js having the following code:
const fs = require("fs");
// If no error
console.log("Data is appended to file successfully.");
}
);
Output:
Data is appended to file successfully.
Example 1: For synchronously appending
const fs = require("fs");
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.
o err: It is an error that would be thrown if the method fails.
Example: Let us create a js file named main.js having the following code:
const fs = require("fs");
Understanding EventEmitter
EventEmitter provides a simple and flexible way to handle events. You can think of it as a publisher-
subscriber pattern where:
• Emitters publish (emit) named events.
• Listeners subscribe to (handle) these events by attaching callback functions.
This mechanism allows for decoupled communication between different parts of an application, enhancing
modularity and scalability.
Syntax:
// Creating a constant reference of EventEmitter
const EventEmittter = require('events');
Since the EvenEmitter class is defined in events module, we must include in the code with require
statement.
When an EventEmitter instance faces any error, it emits an 'error' event. When a new listener is
added, 'newListener' event is fired and when a listener is removed, 'removeListener' event is fired.
1 newListener(event, listener)
• event − String: the event name
• listener − Function: the event handler function
This event is emitted any time a listener is added. When this event is triggered, the
listener may not yet have been added to the array of listeners for the event.
removeListener(event, listener)
• event − String The event name
• listener − Function The event handler function
2
This event is emitted any time someone removes a listener. When this event is
triggered, the listener may not yet have been removed from the array of listeners for
the event.
addListener(event, listener)
1 Adds a listener at the end of the listeners array for the specified event. Returns
emitter, so calls can be chained.
on(event, listener)
2 Adds a listener at the end of the listeners array for the specified event. Same as
addListener.
once(event, listener)
3 Adds a one time listener to the event. This listener is invoked only the next time the
event is fired, after which it is removed
removeListener(event, listener)
Removes a listener from the listener array for the specified event. If any single
4
listener has been added multiple times to the listener array for the specified event,
then removeListener must be called multiple times to remove each instance.
removeAllListeners([event])
Removes all listeners, or those of the specified event. It's not a good idea to remove
5
listeners that were added elsewhere in the code, especially when it's on an emitter
that you didn't create (e.g. sockets or file streams).
setMaxListeners(n)
6 By default, EventEmitters will print a warning if more than 10 listeners are added for
a particular event. Set to zero for unlimited.
listeners(event)
7
Returns an array of listeners for the specified event.
off(event, listener)
9
Alias for removeListener
emitter.emit(eventName, arg1,arg2,...)
Example: Example for creating an EventEmitter and adding events using the addListener method.
// Importing the events module
const EventEmitter = require('events');
Output
welcome Geek
// Creating events
const person1 = (msg) => {
console.log("Message from person1: " + msg);
};
Output
3. Event Requests
Event requests usually refer to requesting an event to occur or be triggered in an asynchronous manner.
This is useful when dealing with HTTP requests or long-running operations that eventually trigger events
after a delay or action is completed.
• Use in HTTP requests: In web servers (like Express), an event request might be triggering a custom event
after processing the HTTP request.
• Long-running processes: For example, you might emit an event after a database query or a file upload is
completed.
It use for:
Example:
const fs = require('fs');
const eventEmitter = new EventEmitter();
Output
Listener 1 received: Sample data
Listener 2 received: Sample data
Once Listeners
The once method adds a listener that is only executed the next time the event is emitted, and then it is
removed.
const EventEmitter = require('events');
const eventEmitter = new EventEmitter();
eventEmitter.once('connect', () => {
console.log('Connected!');
});
Output
Connected!
Removing Listeners
You can remove specific listeners using the removeListener method or remove all listeners for an event
with removeAllListeners.
const EventEmitter = require('events');
const eventEmitter = new EventEmitter();
eventEmitter.on('test', listener);
eventEmitter.removeListener('test', listener);
eventEmitter.emit('test'); // No output