0% found this document useful (0 votes)
36 views89 pages

Node JS

Uploaded by

P.Padmini Rani
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
36 views89 pages

Node JS

Uploaded by

P.Padmini Rani
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 89

Node JS

Node.js is a JavaScript runtime to build fast,

scalable network applications.

It helps us to use JavaScript in server-side

coding.

JavaScript is responsible for most of the client-

side processing in web applications today.


Need of Node.js
Let us look at the below scenarios for understanding the

need for Node.js:


Scenario 1: JavaScript has been the most used language for

creating dynamic web pages. JavaScript has moved to the


server-side too, establishing itself on the web servers as
well.
Node.js also represents the "JavaScript everywhere"
paradigm, by unifying web application development
around a single language, rather than using different
languages for server-side and client-side.
Scenario 2: Consider a scenario where you are trying

to upload videos to a social media website. You may


observe that lot of time is taken for getting your
request processed.
This may be because the preceding requests need to be

completed first by the web server of the application


before executing this new request.
In order to ensure the requests get served concurrently,

multiple approaches have been proposed. This is where


Node.js comes in.
Since Node.js uses an event looping mechanism,

a Node.js web server is capable of sending responses in

a non-blocking way.

This eventually means, a Node.js server can handle a

large number of requests than the commonly used

traditional web servers.


Node.js and its Benefits
 1. Node is popular: Node.js uses JavaScript for application

development. JavaScript is a powerful programming language


as it provides good flexibility to developers.
 2. Full-stack JavaScript development: Node.js has paved the

way for JavaScript to be on the server-side as well.


Hence applications can now have both back-end and front-end
developed with the same JavaScript language. We now have
two popular JavaScript software stacks for building full-stack
web applications: MEAN and MERN.
Node is the N in the MEAN stack. In this
stack, Node is used along with
the MongoDB database and Express, which is
a Node framework for back-end application
development.
Angular framework is used for front-end
application development.
Node is the N in the MERN stack as well. Here,
Node is used along with MongoDB database
and Express for back-end application
development.
React is used for front-end application
development in this stack.
 3. Very fast: Node applications have better performance

than applications developed using other technologies due to


the JavaScript engine used internally in Node. The
engine converts JavaScript code into machine code
and provides extremely fast execution.
 4. Node is powerful: Node uses a non-blocking I/O model

and asynchronous programming paradigm, which helps in


processing requests in a non-blocking way.
 5. Data Streaming: Node has a built-in Streams API that

helps in creating applications where data streaming(reading


and writing) is required.
 6. Rich Ecosystem: Node.js provides a package manager

called NPM (Node Package Manager) which is the world's


largest software registry that helps open source developers
to share and use packages using NPM.
 7. Modularity: Node applications can be developed as
modules which helps in dividing the application into a
reusable set of code.
 8. Wide client-side and database connectivity: Node.js has

absolutely no dependencies and also goes perfectly with any


possible client-side technologies like Angular, React, etc., and
any database like MySQL or MongoDB.
Organizations using Node.js
Node.js is used in applications developed for a wide range

of domains.

All these organizations were using different technologies

like Java, Rails, etc. for developing the server-side of their


applications. But later, they migrated to Node.js because
of the features provided by it.
The below table lists the reasons why they migrated to Node.js.
What is Node.js?
Node.js is an open-source JavaScript run-time
environment used for building scalable network
applications.
It helps in developing the server-side of the application
using JavaScript language. It is used for building data-
intensive real-time applications.
What can we build using Node.js?
1. Complex SPA(Single Page Applications)
2. Real-time applications like Chat rooms
3. Data streaming applications
4. REST APIs
5. Server-side web applications
Features of Node.js
1. V8 engine
As application development in Node uses JavaScript
language, the Node.js platform needs an engine for
executing JavaScript.
The engine used in the platform is V8 which is an open-
source high-performance engine.
It is developed by Google and written in C++.
V8 compiles JavaScript source code into native machine
code.
The performance of the Node.js application is faster due
to this ultra-fast engine used in the platform.
2. Single codebase

Since coding in Node is based on JavaScript, both the

client and the server-side code can be written using the


same JavaScript language.
It allows the front-end and back-end teams to be

combined into a single unit.


Also since Node.js uses JavaScript, we can quickly

manipulate the JSON data retrieved from external web API


sources like MongoDB, hence reducing the processing
time needed per request.
3. Asynchronous and event-driven

All the APIs in Node are asynchronous i.e. non-blocking,

which means Node-based server will never wait for an


API to return data or to complete the request, it will move
to the next request process.
The notification mechanism of Node.js helps in getting

the response from the previous requests after its


completion.
Executing JavaScript code can happen in a Synchronous

or Asynchronous way.
Synchronous programming
In Synchronous programming, the code execution
happens synchronously. This allows only one task to
execute at a time.
Suppose, we need to read the content of a file and
then database operation is to be executed. When the file
read operation is started, the rest of the code in the
program gets blocked until the file reading operation is
finished. Once the file reading is done, then it continues
to execute the remaining code. Though the database
operation code is not dependent on the file read
operation, it is getting blocked. This kind of code is
considered as blocking code or synchronous code.
Asynchronous programming
The asynchronous code will get executed without
affecting other code execution. This allows multiple
tasks to happen at the same time.
Consider the same scenario of reading a file and then
database operation is to be executed.
On asynchronously implementing this, when the file
read operation is started, it will not wait for the read
operation to complete, it will just continue execution of
the rest of the code.
Once the file reading is done, it will be informed and
the corresponding function gets called. This provides a
non-blocking way of executing the code.
This improves system efficiency and throughput.
 In Node.js, asynchronous programming is implemented using
the callback functions.
 Callback function: A callback is a function passed as an
argument to another function and it will be executed after the
task gets completed. It helps in non-blocking code execution.
 setTimeout(() => {
 console.log("after 20 seconds");
 }, 20000);
 setTimeout() takes two arguments. The first argument is the
callback function and the second argument is the delay in
milliseconds. The callback function is called after 20 seconds.
 In Node.js, at the completion of each task, the
respective callbacks written gets invoked. This makes
Node.js highly scalable as it can handle a large number of
requests in a non-blocking way.
4. Single-threaded event loop model

Node.js is said to be highly scalable because it handles

the client request using the Single-threaded model with


an event loop. Node environment follows the Single
Threaded Event Loop Model which is based
on JavaScript's callback mechanism.
Single-threaded model with the event loop of Node.js
Single-threaded event loop model processing
steps:
Step 1: Assume 'n' number of clients, send requests to the
webserver to access the web application concurrently.
Node web server receives those requests and places them
into a queue known as "Event Queue".
The Node web server internally maintains a limited thread
pool to provide service to the client. Let us assume that
'm' number of threads can be created and maintained.
Step 2: The Node web server internally has a component,
known as "Event Loop". It uses the indefinite loop to receive
requests and process them. But the Event loop component
uses a "Single Thread" to process the requests.
Step 3: The event Loop component checks for any client

request that is placed in the Event Queue. If no requests


are present, then it waits for incoming requests. If the
requests are present, then it picks up one client request
from the Event Queue and starts processing that request.
Step 4: If that client request does not require any
blocking I/O operations, then the request is processed till
completion and the response is sent back to the client.
Step 5.1: If the client request requires some blocking

I/O operations like file operations, database interactions,


any external services then it checks the availability of
threads from the internal thread pool.
Step 5.2: One thread is assigned from the internal pool

of threads and assigned to the client request. That thread


is responsible for taking that request, processing it,
and performing blocking I/O operations.
Step 6: After processing the request, the response is

prepared and sends back to the Event Loop. Event Loop


then sends that response back to the requested client.
 5. Scalability
 Scalability is that it makes use of event-driven programming
with the Single Threaded Event Loop Mechanism. This
enables the Node application to serve a huge number of
incoming requests concurrently and it scales up
automatically to serve those requests efficiently.
 6. I/O bound operations
 Due to its asynchronous/non-blocking nature, Node.js can
be used to create I/O bound applications that involve huge
input-output operations, such as creating real-time
applications that have real-time data flowing in.
Applications like Facebook, online chat applications, and
Twitter are a few examples.
 An online marketing company like eBay makes use of
Node.js to handle lots of I/O-bound operations to handle
eBay-specific services that display information on the page.
7. Streaming of data
Node.js has a built-in Stream API available, using which
we can stream the data very fast. Applications like the
Twitter stream, video stream, etc. use this feature.
Media companies like National Public Radio, Direct TV,
HBO makes use of Node.js to stream the data to their
viewers.
8. Modularity
Node.js supports modular JavaScript. Instead of writing
code in a single JavaScript file, the code can be written in
modules which can then be accessed at multiple places in
the application. This helps in easy maintenance and
reusability of the code.
Where to use Node.js and where not to?

If an application involves a lot of calculations that

require CPU for processing, is not fit for Node.js.


Node.js shines well for applications that involve lots

of I/O bound operations.


Node.js in the web application stack
Now let us take a look at the position of Node.js in the

web application stack.


Node.js places itself in the server-side in the complete

web application stack and provides a complete server-


side solution for application development.
Node.js works well with any client-side technology

like Angular, React, etc. and any database like


MongoDB, MySQL, etc. can be used for data storage.
How to use Node.js
Download Node.js from the official site.

It is important to download the stable version while

installing, as the Node.js team keeps upgrading the


version by adding new features and enhancements.
To check whether Node.js is installed or not in your

machine, open the Node command prompt and check


the Node.js version by typing the following command.

node -v
 The flag -v will display the version of Node.js installed in the

machine.

 Node.js also provides a package manager called NPM(Node

Package Manager) which is a collection of all open-source


JavaScript libraries. It helps in installing any library or
module into your machine.
 Thus we have successfully installed Node.js in the machine and

we can start the application development using Node.js.


Highlights:

Creating a JavaScript file

Executing the JavaScript file using Node.js

Demo steps:

Now that we know how to install the Node.js platform in

our machine, let us create our first Node.js program.


 Step 1: Create a folder NodeJS in D drive and create a

new JavaScript file, first.js inside the folder. Type the


below code inside the JavaScript file.
console.log("My First Node.js program");
Step 2: Navigate to the created NodeJS folder in the
NodeJS command prompt and execute the JavaScript file,
first.js using the node command.
node first.js
Step 3: After the successful interpretation of the code, we
can see the output in the Node.js command prompt.
Visual Studio Code IDE
You can also open the NodeJS folder, in Visual Studio Code
IDE. To execute the first.js file, open the integrated
terminal and issue the command for executing the file. You
will get the output as shown below:

Let us now see how to execute a JavaScript file that


contains code for browser interaction through Node.js.
JavaScript code executable in Node.js
Let us make a small modification to the code written in

the first.js created earlier.


document.write("My first Node.js program!");

We have replaced console.log() with document.write().

The document.write() function displays output on the

browser screen. While interpreting the first.js using


Node.js now, we will encounter an error as shown below:
So, we can now conclude that any JavaScript file which
doesn't contain codes for browser interactions will execute
successfully using the Node platform.
Create web server in Node.js – Demo
 Highlights:
 Using require() and createServer() method
 Running a web server in Node.js
Demosteps:
 Step 1: Create a new JavaScript file httpserver.js and include the
HTTP module.
const http = require("http");
 Step 2: Use the createServer() method of the HTTP module to
create a web server.
 var server = http.createServer((req, res) => {
 res.write("Hello World! I have created my first server!");
 res.end();
 });
 server.listen(3000);
 console.log("Server started... Running on localhost:3000");
Step 3: Save the file and start the server using
the node command. When the file executes successfully,
we can observe the following output in the console.

Step 4: We will observe the following in the browser.

Thus we have created a Node server and sent the


response from the server to the client.
Introduction to Node Package Manager
We saw the usage of one of the built-in modules in
Node.js: HTTP module. There are many other built-in
modules as well, provided by Node.js for implementing
various functionalities.
It is also possible to import an external module into a
Node application, using NPM (Node Package Manager).
What is NPM?
NPM stands for Node Package Manager which is a
collection of all the open-source JavaScript libraries
available in this world. It is the world’s largest software
registry maintained by the Node.js team. There are many
packages available on NPM which can be used in our
application development.
 The npm CLI
 NPM provides a command-line interface "npm" to work with the
NPM repository, which comes bundled with Node. This tool can be
used to install, update, or uninstall any package through NPM.
 How to get the packages to be installed in our application?
 To install any NPM package use the below code in the command
prompt:
npm install <package_name>[@<version>]
 This will create a folder node_modules in the current directory
and put all the packages related files inside it. Here @version is
optional if you don't specify the version, the latest version of the
module will be downloaded.
 You can even get tools from NPM like @angular/cli, typescript
(compiler), etc.
 There are two modes of installation through NPM
 Global
 Local
Global installation
If we want to globally install any package or tool add -g to
the command. On installing any package globally, that
package gets added to the PATH so that we can run it
from any location on the computer.
npm install -g <package_name>
Consider the scenario where "express" which is the most
popular framework of Node to be used in our application.
Then it can be installed using NPM as below.
npm install -g express
To install any package that is to be available from
anywhere on the computer, then better to go for global
installation.
 Local installation

 If we do not add -g to your command for installation, the

modules get installed locally, within a node_modules folder


under the root directory. This is the default mode, as well.

npm install express


 To install any application-specific package, get it installed

locally.
 Best Practice Tip: Start all projects with npm init. This will

create a new package.json for you which allows you to add a


bunch of metadata to help others working on the project have
the same setup as you.
How to update the packages in our application?
We can also update the packages downloaded from the

registry to keep the code more secure and stable.


To update a locally installed package, navigate to the

folder the package is installed and run the below


command.
npm update

Any update for a global package can be done using the

following command.
npm update -g <package_name>
How to uninstall the packages in our application?
We can uninstall the package or module, which we

downloaded using the following command.


npm uninstall <package_name>[@<version>]

npm uninstall express@2.1.0

NPM Alternatives

NPM is one of the oldest package managers for Node.js.

There are other replacements like YARN that works with


the NPM registry.
What is package.json file?
A Node project needs a configuration file named
"package.json". It is a file that contains basic information
about the project like the package name, version as well
as more information like dependencies which specifies
the additional packages required for the project.
To create a package.json file, open the Node command

prompt and type the below command.


npm init
Enter values for package name, version, description, and
so on. This will generate a package.json file similar to the
one shown below:
{ "name": "mypackage",
"version": "1.0.0",
"description": "\"Testing publishing\"",
"main": "index.js",
"scripts": {
"test": "echo \
"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC“
}
The name and version represent the module name and

the version to be used while publishing.


The description represents a brief description of the

module.
The property main represents the entry point of the

application.
The test represents all the test scripts to run.

The author represents the author's name and the

license represents the license type of the module.


Publish custom module to NPM-Demo
The NPM repository has a collection of modules that we
can download and use in our application.
It is also possible to publish the custom modules that we
created to NPM so that we can make our modules to be
available for others to download.
Let us understand how to publish a custom module to
the NPM repository.
Steps to publish a custom module to NPM:
Step 1: Create a user account using the signup option in
npmjs.com or using npm adduser command from the
command prompt as below:
D:\>npm adduser
Step 2: Create a package.json file in a folder named
mypackage.
Specify application configurations in this file.
{ "name": "mypackage",
"version": "1.0.0",
"description": "Testing publishing",
"main": "webServer.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": ["node” ],
"author": "",
"license": "ISC"}
Step 3: Create a module in the same folder inside which
the package.json file resides.
MyModule.js
exports.myMethod = function () {
console.log('Method invoked from a module');
};
Create another file where MyModule is to be imported and
invoke the myMethod() function.
TestModule.js
const myModule = require('./MyModule');
myModule.myMethod();
Step 4: Run the code using the Node command and test it.
D:\mypackage\>node TestModule.js
Step 5: Use npm publish command from the command

prompt to publish the module to npm:


D:\mypackage\>npm publish + mypackage@1.0.1

The package will be published successfully. To use this

module from npm, just use the "npm install


mypackage" command from the command line and it
will get installed.
Node Package Manager
 Highlights:
 Usage of NPM
 Installing a module using NPM
 Demo steps:
 Step 1: Write the following statement in your terminal in order
to install the express module using npm.
npm install -g express
 Step 2: You can observe the following in your integrated
terminal.

 Thus express module will be installed in the machine. Similarly,


any other module can be installed through the npm repository.
NPM audit
To perform a quick security check know, as a moment-in-
time review of your application, we can make use of npm
audit which generates a report on the dependencies of
your application. This report consists of security threats to
your application and can help you fix vulnerabilities by
providing npm commands and recommendations for
further troubleshooting.
Example:-
running npm audit against myApp:
cd myApp
npm audit
Modularizing Node application
In an Enterprise application, it is not possible to have all
the logic written in a single file.
As the complexity of the program increases, it reduces
the readability and maintainability of the application.
In this kind of environment, it is easy to lose track of what
a particular code does or to produce reusable code.
So the application needs to be created in
a modularized fashion.
What is modularization?
Modularization is a software design technique in which
the functionality of a program is separated into
independent modules, such that each module contains
the desired functionality.
Advantages of Modularization
Readability: Modular code highly organizes the program
based on its functionality. This allows the developers to
understand what each piece of code does in the
application.
Easier to debug: When debugging large programs, it is
difficult to detect bugs. If a program is modular, then each
module can be debugged easily by the programmer.
Reusable Code: Modular code allows programmers to
easily reuse code to implement the same functionality in
a different program.
Reliability: Modular code will be easier to read. Hence it
will be easier to debug and maintain the code which
ensures smoother execution with minimum errors.
Node environment provides many built-in modules that
can be used in application development.
We have already seen the usage of the "HTTP" module,
which is a built-in module in Node.js for creating a web
server.
Node.js also provides many other useful modules like fs
module (used for file-related operations), os
module(used for operating system-related functions), net
module( used for socket programming), etc. for server-
side application development.
Let us explore how to modularize an application in
Node.
How to modularize code?
Consider a simple Node.js application with a Javascript
file calculator.js with the below code:
calculator.js
 async function add(operator1, operator2)
{
 return 'Result: ', operator1 + operator2;
}
 async function substract(operator1, operator2)
{
 return 'Result: ', operator1 - operator2;
}
 async function asyncCall()
{
 console.log('calling');
 const result = await add(2, 3);
 console.log(result);
}
 asyncCall();
By default the functions declared in one module are

visible only in that specific module.


In order to export the functionalities of one module into

another, Node.js has provided an object called "exports".


This object is a built-in object of Node.js to which all the

functionalities are to be attached.


We can assign the function reference to
the exports object, which can be written as:
exports.add = async (operator1, operator2) => {

 console.log("Result:", operator1 + operator2);

};

exports.subtract = async (operator1, operator2) => {

 console.log("Result:", operator1 - operator2);

};

Now we have exported the functions in the calculator.js

file, let us see how to import it in another file.


Importing a module
Let us now understand how to import
the calculator.js file into another file.
Consider another file tester.js, where we need to import
and use the functions in the calculator.js file.
Use require() function and specify the module name to
be imported as shown below:
const myCalculator = require("./Calculator");
The require() function takes the path of the file as a
parameter and returns an exports object. Now in order
to use the methods of calculator.js add the below code in
the tester.js file:
myCalculator.add(10, 30);
myCalculator.substract(30, 10);
On executing the tester.js file, we will get the following
output:
Creating a module in Node
Highlights:
Creating a module
Loading the module
Demosteps:
Step 1: Create a file DBModule.js within the NodeJS
folder created earlier.
exports.authenticateUser = (username, password) => {
if (username === "admin" && password === "admin")
{ return "Valid User";
}
else return "Invalid User";
};
 Step 2: Modify the file httpserver.js file created earlier as
below.
 app.js
 const http = require("http");
 var dbmodule = require("./DBModule");
 var server = http.createServer((request, response) => {
 result = dbmodule.authenticateUser("admin", "admin");
response.writeHead(200, { "Content-Type": "text/html" });
 response.end("<html><body><h1>" + result +
"</h1></body></html>");
 console.log("Request received");});
 server.listen(3000);
 console.log("Server is running at port 3000");
 In the httpserver.js file, we are loading the module "DBModule"
and then invoking the function named "authenticateUser()".
Step 3: Run the httpserver.js using the node command.

Open a browser and navigate to URL


"http://localhost:3000" and observe the output.
Restarting Node Application
Whenever we are working on a Node.js application
and we do any change in code after the application is
started, we will be required to restart the Node process
for changes to reflect.
In order to restart the server and to watch for any code
changes automatically, we can use the Nodemon tool.
Nodemon: is a command-line utility that can be executed
from the terminal.
It watches the application and whenever any change is
detected, it restarts the application.
To install it in the application, run the below command.
npm install nodemon -g
Once the 'nodemon' is installed in the machine, the

Node.js server code can be executed by replacing the


command "node" with "nodemon".

nodemon app.js
Thus the 'nodemon' starts the application in watch

mode and restart the application when any change is


detected.
const http = require("http");
var server = http.createServer((req, res) => { res.write("Hello
World! I have created my first server!"); res.end();
});
server.listen(3000);
console.log("Server started... Running on localhost:3000");
Observe the console on starting the nodemon in a command
prompt window.
Now open the application code and do changes in the code
as below.
const http = require("http");
var server = http.createServer((req, res) =>
{ console.log("Request URL is " + req.url);
res.write("Hello World! I have created my first server!");
res.end();
});
server.listen(3000);
console.log("Server started... Running on
localhost:3000");
Observe the console message in the command prompt.
Nodemon automatically restarted the server on observing
changes in the code.

Best Practices Tip: To avoid over and over restarting of


server for small changes to reflect. It is important to have
an automatic restart of the server of your application. Use
nodemon for this purpose.
Need for File system module
The user wants to store the information about the
requested URLs to the application/errors that occurred in
the application.
To store this information, the user can choose any of the
following methodologies:
 File
 Database
Storing log details in the Database is not an optimal
solution because it may increase the number of API calls for
DB interaction. This will impact the performance of the
application.
The best solution to use the file system, here. The
information will be stored locally in the application without
impacting the performance of the application.
fs Module
One of the important operations in server-side
programming is to be able to read or write the content of
a file.
Node.js comes with the file system (fs)
module fs to perform file operations.
It provides many useful functionalities to interact with
the file system.
How to use fs module?
To include the File System module, use the require()
method:
const fs = require('fs');
Once imported, we can use different methods provided
by this module for doing any file manipulations.
fs module – Operations
Some of the file operations are:
Writing data to a file
Reading data from a file
Updating content in a file
Writing data to a file:
The File System module has the following methods for
creating a new file and writing data to that file:
writeFile()
appendFile()
The fs.writeFile() method will overwrite the content if the
content already exists.
If the file does not exist, then a new file will be

created with the specified name and content.


Syntax:

fs.writeFile(file, data, callback);


file: Placeholder to give the file name in which you are

going to write the data.


data: The data/content must be written to the file.

callback: The callback method, that will be executed,

when 'writeFile()' function is executed. This callback will


be executed in both success as well as failure scenarios.
Writing data to a file – Async/Await
 Method 1:
 Before Node.js v8, If we want to avoid callbacks, we have to
manually promisify the fs.writeFile function.
 Let's manually promisify and wrap it in a function:
 //Method 1 // promisifing writeFile method
 const fs = require('fs');
 const writeFilePromise = (file, data) => {
 return new Promise((resolve, reject) => {
 fs.writeFile(file, data, (err) => {
 if (err)
 reject('Could not write file');
 resolve('success'); });
 });
 };
//Invoking the promise which we have created.
Self-invocation
function(async () => {
try {
await writeFilePromise('myData.txt', `Hey @ ${new
Date()}`);
console.log('File created successfully with promisify
and async/await!');
}
catch (err) {
console.log(err);
}
})();
 Method 2:
 In the latest versions of Node.js, 'util.promisify()' will allow us to
convert I/O functions that return callbacks into I/O functions
that return promises.
 // Method 2
 const fs = require('fs');
 const { promisify } = require('util');
 const writeFile = promisify(fs.writeFile);
 (async () => {
 try {
 await writeFile('myData.txt', `Hey @ ${new Date()}`);
 console.log('File created successfully with promisify and async/
await!');
}
 catch (err) { console.log(err); }
 })();
Appending data to a file
The appendFile() method first checks if the file exists or
not. If the file does not exist, then it creates a new file with
the content, else it appends the given content to the
existing file.
Syntax:
fs.appendFile(path, data, callback)
path: Placeholder to give the file name in which you are
going to append the data.
data: The data/content which must be appended to the
file.
callback: The callback method, that will be executed,
when 'appendFile()' function is executed. This callback will
be executed in both success as well as failure scenarios.
 You might have an existing file from the previous demo, paste the
below code in that file.
 const fs = require('fs');
 const { promisify } = require('util');
 const appendFile = promisify(fs.appendFile);
 (async () => {
 try {
 await appendFile('myData.txt', `\nHey @ ${new Date()}`);
 console.log(
 'File content appended successfully with promisify and
async/await!'
 );
 } catch (err) {
 console.log(err);
 }
 })();
Save the file and run the code using the node

command. Open the myData.txt file, we can


observe that the new log information has been
appended to the file.
Try out some more: Delete the myData.txt file

and re-run the code multiple times with various


different inputs and observe.
Reading data from a file
The fs.readFile() method is used to read the content from
a given file.
Syntax:
fs.readFile(path, encoding, callback);
path: Path where the file with data/content resides, with
respect to the root folder.
encoding: an optional parameter that specifies the type of
encoding to read the file. Possible encodings are 'ascii',
'utf8', and 'base64'. If no encoding is provided, the default
is utf8.
callback: The callback method, that will be executed,
when readFile() function is executed.
Consider the below sample code for reading data from a
file "myData.txt".
const fs = require('fs');
const { promisify } = require('util');
const readFile = promisify(fs.readFile);
(async () => {
try {
const fileData = await readFile('myData.txt', 'utf8');
console.log(fileData);
}
catch (err) {
console.log(err);
}
})();
Demo: Writing data to a file
 Highlights:
 Usage of fs.writeFile() method
 To 'write' data to a file
 Step 1: Create a file fileSystem.js and paste the below code in the
file.
 const fs = require('fs');
 const { promisify } = require('util');
 const writeFile = promisify(fs.writeFile);
 (async () => {
 try {
 await writeFile('myData.txt', `Hey @ ${new Date()}`);
 console.log('File created successfully with promisify and
async/await!');
}
 catch (err) { console.log(err); }
 })();
Step 2: Run the above code using node command 'node
fileSystem.js' to see the output.

Step 3: Check in the folder in which "fileSystem" file


resides. You can observe that a new file
named myData.txt has been automatically created logging
the string content and date.

Step 4: Provide different values in the data/content part


of the writeFile() function and observe
the ‘myData.txt' file.
Step 5: You might have observed that the file content is

getting replaced with the latest data, whenever you run


this code.
The writeFile() method has overwritten the previous

content. To resolve this, we will


use appendFile() method.
Demo - Appending data to a file

 Highlights:

 Usage of fs.appendFile() method

 To append data to a file

 Demosteps:

 Step 1: Create a file log.js and paste the below code in the file.

 The appendFile() method first checks if the file exists or not.

If the file does not exist, then it creates a new file with the
content, else it appends the given content to the existing file.
const fs = require('fs');
const { promisify } = require('util');
const appendFile = promisify(fs.appendFile);
(async () => {
try {
await appendFile('myLogger.txt', `Request received @ $
{Date()} \n`);
console.log('File content appended successfully');
}
catch (err) { console.log(err);
}
})();
Step 2: Run the above code using node command 'node
log.js' to see the output.

Now that we have learned about writing and appending


data to a file, let us learn about reading data from a file.
Demo - Reading data from a file
 Highlights:
 Usage of fs.readFile() method to read the content of file.
 Demosteps:
 Step 1: Create a JavaScript file 'fileSystem.js' and add the below code:
 const fs = require('fs');
 const { promisify } = require('util');
 const readFile = promisify(fs.readFile);
 (async () => {
 try {
 const fileData = await readFile('demo.txt', 'utf8');
console.log(fileData);
}
 catch (err) { console.log(err); }
 })();
Step 2: Create a file demo.txt and add the following text.
Node.js is an open-source JavaScript run time
environment which helps the developers to build fast,
scalable network applications. Express is a very popular
framework for Node.js, which simplifies the Node
application development.
Step 3: Run the file 'fileSystem.js' and observe the output
in the console.
THANK YOU

You might also like