0% found this document useful (0 votes)
3 views18 pages

unit-II

Node.js modules are encapsulated code blocks that can be reused across applications, allowing for better organization and maintainability. They can be categorized into core modules, local modules, and third-party modules, each serving different purposes in application development. Additionally, Node.js provides a Buffer class for handling binary data and NPM for managing packages and dependencies.

Uploaded by

shitalbandal445
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
3 views18 pages

unit-II

Node.js modules are encapsulated code blocks that can be reused across applications, allowing for better organization and maintainability. They can be categorized into core modules, local modules, and third-party modules, each serving different purposes in application development. Additionally, Node.js provides a Buffer class for handling binary data and NPM for managing packages and dependencies.

Uploaded by

shitalbandal445
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 18

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.

Types of Node.JS Modules


1. 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');
The require() function will return a JavaScript type depending on what the particular module returns. The following example
demonstrates how to use the Node.js http module to create a web server.
const http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.write('Welcome to this page!');
res.end();
}).listen(3000);

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

What is Node.js buffer?


In Node, Buffer is used to store and manage binary data. Pure JavaScript is great with Unicode-encoded strings,
but it does not handle binary data very well. It is not problematic when we perform an operation on data at the
browser level but at the time of dealing with TCP stream and performing a read-write operation on the file system
is required to deal with pure binary data.
To satisfy this need Node.js uses Buffer to handle the binary data. So in this article, we are going to know about
buffer in Node.js.
What is Buffer in Node?

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:

const buf = Buffer.alloc(100); // Creating a new Buffer


const len = buf.write("Hello world!"); // Writing to the Buffer
// len is now 12
The Buffer.write() function returns the length of the string, which is stored in the buffer.
Buffer.byteLength()

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.

There are three main npms:


• npm is the original node package manager and is the most widely used. It is maintained by the
Node Foundation and has a large community of users and developers.
• Yarn is an updated npm that is faster and more reliable than npm, and it has a several features that
npm does not, such as workspaces and improved performance.
• pnpm is a newer npm that is designed to be faster and more efficient than npm and Yarn. It uses a
different package resolution algorithm that can significantly reduce the amount of time it takes to
install packages.
Here are some of the benefits of using an npm:

• 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.

D:\nodejs\newnodeapp>npm install express –save

The package.json file in this folder will be updated to −

{
"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

Install Package Globally


Globally installed packages/dependencies are stored in system directory. Such dependencies can be used
in CLI (Command Line Interface) function of any node.js but cannot be imported using require() in Node
application directly.
npm install express -g
This will produce a similar result but the module will be installed globally. On Linux, the global packages
are placed in /usr/lib/node_modules folder, while for Windows, the path is C:\Users\your-
username\AppData\Roaming\npm\node_modules.

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.

npm update <package name>

The following command will update the existing ExpressJS module to the latest
version.

PS D:\nodejs\newnodeapp> npm update express

up to date, audited 63 packages in 2s

11 packages are looking for funding


run `npm fund` for details

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.

Adding dependencies to a package.json file from the command line


To add dependencies and devDependencies to a package.json file from the command line, you
can install them in the root directory of your package using the --save-prod flag (also -S) for
dependencies (the default behavior of npm install) or the --save-dev flag (also -D) for
devDependencies.

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

Manually editing the package.json file


To add dependencies to a package.json file, in a text editor, add an attribute
called "dependencies" that references the name and semantic version of each dependency:
{
"name": "my_package",
"version": "1.0.0",
"dependencies": {
"my_dep": "^1.0.0",
"another_dep": "~2.2.0"
}
}
To add devDependencies to a package.json file, in a text editor, add an attribute
called "devDependencies" that references the name and semantic version of each devDependency:
"name": "my_package",
"version": "1.0.0",
"dependencies": {
"my_dep": "^1.0.0",
"another_dep": "~2.2.0"
},
"devDependencies" : {
"my_test_framework": "^3.1.0",
"another_dev_dep": "1.0.0 - 1.2.0"
}

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.

What is Synchronous and Asynchronous approach?


Synchronous approach:
They are called blocking functions as it waits for each operation to complete, only after that, it executes the
next operation, hence blocking the next command from execution i.e. a command will not be executed until
& unless the query has finished executing to get all the result from previous commands.
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
i.e. each command will be executed soon after the execution of the previous command. While the previous
command runs in the background and loads the result once it is finished processing the data.

Example of asynchronous and synchronous:


Create a text file named input.txt with the following content:
GeeksforGeeks: A computer science portal
Now let us create a js file named main.js with the following code:
const fs = require("fs");

// 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");

// Asynchronous - Opening File


console.log("opening file!");
fs.open("input.txt", "r+", function (err, fd) {
if (err) {
return console.error(err);
}
console.log("File open successfully");
});
Output:
opening file!
File open successfully

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);

console.log("opening an existing file");


fs.open("input.txt", "r+", function (err, fd) {
if (err) {
return console.error(err);
}
console.log("File opened successfully!");
console.log("reading the file");

fs.read(fd, buf, 0, buf.length, 0, function (err, bytes) {


if (err) {
console.log(err);
}
console.log(bytes + " bytes read");

// Print only read bytes to avoid junk.


if (bytes > 0) {
console.log(buf.slice(0, bytes).toString());
}
});
});
Output:
opening an existing file
File opened successfully!
reading the file
40 bytes read
GeeksforGeeks: A computer science portal

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");

console.log("writing into existing file");


fs.writeFile("input.txt", "Geeks For Geeks", function (err) {
if (err) {
return console.error(err);
}

console.log("Data written successfully!");


console.log("Let's read newly written data");

fs.readFile("input.txt", function (err, data) {


if (err) {
return console.error(err);
}
console.log("Asynchronous read: " + data.toString());
});
});
Output:
writing into existing file
Data written successfully!
Let's read newly written data
Asynchronous read: Geeks For Geeks

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");

let data = "\nLearn Node.js";

// Append data to file


fs.appendFile(
"input.txt", data, "utf8",
// Callback function
function (err) {
if (err) throw err;

// 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");

const data = "\nLearn Node.js";

// Append data to file


fs.appendFileSync("input.txt", data, "utf8");
console.log("Data is appended to file successfully.");
Output:
Data is appended to file successfully.
• Before Appending Data to input.txt file:
GeeksforGeeks: A computer science portal
• After Appending Data to input.txt file:
GeeksforGeeks: A computer science portal
Learn Node.js

Closing the File


The fs.close() method is used to asynchronously close the given file descriptor thereby clearing
the file that is associated with it. This will allow the file descriptor to be reused for other files.
Calling fs.close() on a file descriptor while some other operation is being performed on it may lead
to undefined behavior.
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.
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:
// Close the opened file.
fs.close(fd, function (err) {
if (err) {
console.log(err);
}
console.log("File closed successfully.");
});
Output:
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.
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");

console.log("deleting an existing file");


fs.unlink("input.txt", function (err) {
if (err) {
return console.error(err);
}
console.log("File deleted successfully!");
});
Output:
deleting an existing file
File deleted successfully!
Benefits
• Enables efficient reading, writing, and updating of files.
• Supports a wide range of file system operations.
• Provides detailed error messages to help with troubleshooting.

What is EventEmitter in Node.js ?


Node.js is known for its asynchronous, event-driven architecture, which allows for handling multiple
operations without blocking the execution of other tasks. At the heart of this architecture is
the EventEmitter class from the events module. The Node.js API is based on an event-driven architecture. It
includes the events module, which provides the capability to create and handle custom events. The event
module contains EventEmitter class.
The EventEmitter object emits named events. Such events call the listener functions. The Event Emitters have
a very crucial role the Node.js ecosystem. Many objects in a Node emit events, for example, a net.Server
object emits an event each time a peer connects to it, or a connection is closed. The fs.readStream object emits
an event when the file is opened, closed, a read/write operation is performed. All objects which emit events
are the instances of events.EventEmitter.

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');

// Initializing instance of EventEmitter


const emitter = new EventEmitter();
Key Concepts of EventEmitter
• Emitting Events: When an event is emitted, all listeners that have been registered for that event are
invoked.
• Listening to Events: You can register listeners (callback functions) for specific events. These listeners are
called when the corresponding event is emitted.
• Removing Listeners: You can also remove listeners if they are no longer needed, which helps in
managing resources efficiently.

Since the EvenEmitter class is defined in events module, we must include in the code with require
statement.

var events = require('events');

To emit an event, we should declare an object of EventEmitter class.

var eventEmitter = new events.EventEmitter();

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.

Sr.No. Events & Description

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.

Following instance methods are defined in EventEmitter class −

Sr.No. Events & Description

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.

emit(event, [arg1], [arg2], [...])


8 Execute each of the listeners in order with the supplied arguments. Returns true if the
event had listeners, false otherwise.

off(event, listener)
9
Alias for removeListener

Creating a listening event using addListener


Before we emit an event we have to create a listener who will listen to the callbacks emitted, then the listener
will proceed with the further actions that are required to comply with the event. We can create an event
listener with the help of the addListener property of EventEmitter. The addListener appends the event to the
end of the array so we can call it multiple times to call multiple instances of the event and is very useful as we
don’t require to write an event multiple times.
Emitting event:
As every event is a named event in node.js we can trigger an event by using the emit method and we can pass
arbitrary arguments to listen in the event.
Syntax:
emitter.addListener(eventName, listener);

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');

// Initializing instance of EventEmitter to be used


const emitter = new EventEmitter();

// Adding listener to the event


emitter.addListener('welcomeEvent', (name) => {
console.log("welcome " + name);
});

// Emitting the welcomeEvent


emitter.emit('welcomeEvent', "Geek");

Output

welcome Geek

Removing an instance of an event


We can remove an event using two methods removeListener if we want to remove a specific listener from the
event or remove all listeners if we want to remove an instance of all listeners from an event.
Syntax:
// For removing any single listener form the event
emitter.removeListener(eventName, listener)

// For removing all listeners of the event


emitter.removeAllListeners(eventName)
Example: Example for removing the event listener of an event.
// Importing the events module
const EventEmitter = require('events');

// Initializing instance of EventEmitter to be used


const emitter = new EventEmitter();

// Creating events
const person1 = (msg) => {
console.log("Message from person1: " + msg);
};

const person2 = (msg) => {


console.log("Message from person2: " + msg);
};

// Registering person1 and person2 with the printEvent


emitter.addListener('printEvent', person1);
emitter.addListener('printEvent', person2);

// Triggering the created event


emitter.emit('printEvent', "Event occurred");

// Removing all the listeners associated with the event


emitter.removeAllListeners('printEvent');
// Triggering the event again but no output
// as all listeners are removed
emitter.emit('printEvent', "Event occurred");

Output

Message from person1: Event occurred


Message from person2: Event occurred
As you can see in the above output event was triggered twice but the output came only once as we deleted the
event listeners so no listeners were present while emitting the event a second time.

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:

• Responding to external events like user input or file uploads.


• Processing asynchronous tasks and notifying other parts of the system when they are complete.

Example:
const fs = require('fs');
const eventEmitter = new EventEmitter();

eventEmitter.on('fileRead', (data) => {


console.log('File read completed:', data);
});

fs.readFile('file.txt', 'utf8', (err, data) => {


if (err) throw err;
eventEmitter.emit('fileRead', data);
});

Advanced Features of EventEmitter


EventEmitter also supports advanced features such as handling multiple listeners, error handling, and more.
Adding Multiple Listeners
You can add multiple listeners for the same event, and they will be called in the order they were added.
const EventEmitter = require('events');
const eventEmitter = new EventEmitter();

eventEmitter.on('data', (data) => {


console.log('Listener 1 received:', data);
});

eventEmitter.on('data', (data) => {


console.log('Listener 2 received:', data);
});

eventEmitter.emit('data', 'Sample data');

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!');
});

eventEmitter.emit('connect'); // Output: Connected!


eventEmitter.emit('connect'); // No output

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();

const listener = () => {


console.log('This will be removed.');
};

eventEmitter.on('test', listener);
eventEmitter.removeListener('test', listener);
eventEmitter.emit('test'); // No output

Best Practices for Using EventEmitter


• Limit Number of Listeners: Keep the number of listeners low to avoid memory leaks.
Use setMaxListeners to control the maximum listeners.
• Handle Errors Properly: Always provide error listeners to catch and handle errors gracefully.
• Remove Unused Listeners: Clean up listeners when they are no longer needed to free up resources.
• Use Descriptive Event Names: Use meaningful and descriptive names for events to make the code more
readable and maintainable.

You might also like