0% found this document useful (0 votes)
23 views

DOC_LM_Unit5 (2)

This document provides an overview of Node.js, including its concepts, features, and applications, as well as instructions for setting up a Node.js server and using built-in and third-party modules. It discusses the advantages and disadvantages of Node.js, its architecture, and the workflow of a web server developed with it. Additionally, it covers the installation process, creating servers, and the use of core and local modules in Node.js applications.

Uploaded by

patelhani5544
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

DOC_LM_Unit5 (2)

This document provides an overview of Node.js, including its concepts, features, and applications, as well as instructions for setting up a Node.js server and using built-in and third-party modules. It discusses the advantages and disadvantages of Node.js, its architecture, and the workflow of a web server developed with it. Additionally, it covers the installation process, creating servers, and the use of core and local modules in Node.js applications.

Uploaded by

patelhani5544
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

Unit-5: Node.

js :
5.1 Concepts, working and Features
5.1.1 Downloading Node.js
5.2 Setting up Node.js server(HTTP server)
5.2.1 Installing on window
5.2.2 Components
5.2.2.1 Required modules, Create Server(http.createServer())
5.2.2.2 Request and response
5.3 Built-in Modules
5.3.1 require() function
5.3.2 User defined module: create and include
5.3.3 HTTP module
5.4 Node.js as Web-server:
5.4.1 createServer() , writeHead() method
5.4.2 Reading Query String, Split Query String
5.5 File System Module:
5.5.1 Read Files (readFile())
5.5.2 Create Files(appendFile(),open(),writeFile())
5.5.3 Update Files(appendFile(),writeFile())
5.5.4 Delete Files(unlink())
5.5.5 Rename Files(rename())

Concepts, working and Features


▪ It is basically runtime environment which is run on server like php, angular, react etc.
▪ As an asynchronous event-driven JavaScript runtime, non-blocking I/O, making it
lightweight, efficient, and extremely fast for developing web apps.
▪ NodeJs is a powerful Javascript-based platform built on Chrome’s Javascript V8 Engine.
Node.js was developed by Ryan Dahl in 2009.
▪ It is used to develop I/O intensive web applications like video-streaming websites, one-
page applications, and other web applications.
▪ It is an open-source, free and cross-platform which allows execution of Javascript code
outside a web-browser.
▪ Node.js has its core part written in C and C++. Node js is based on a single-threaded event
loop architecture which allows Node to handle multiple client requests

Applications of Node.js
▪ The following are some of the areas where Node.js is proving to be an effective
technology partner-
o Single Page Applications
o Data-Intensive Real-time Applications
o I/O bound Applications
o JSON APIs based Applications
o Data Streaming Applications
Advantages:
1. High performance for real-time applications.
2. Easy scalability
3. Cost effective

By: Dr. Ami Desai 1


4. Community support to simplify development (Open-source)
5. Easy to learn and quick to adapt.
6. Improves Application’s response time and boosts performance.
7. Extensibility to Meet Customized Requirements
8. Reduces Loading Time by Quick Caching
9. Helps in Building Cross-Platform Applications

Disadvantages:
1. Reduces performance when handling Heavy Computing Tasks
2. Node.js invites a lot of code changes due to Unstable API
3. Node.js Asynchronous Programming Model makes it difficult to maintain code
4. Choose Wisely – Lack of Library Support can Endanger your Code
5. High demand with a few Experienced Node.js Developers

Node.js Architecture:

Node.js uses the “Single Threaded Event Loop” architecture to handle multiple concurrent
clients. Node.js Processing Model is based on the JavaScript event-based model along with
the JavaScript callback mechanism.
Now let’s understand each part of the Node.js architecture and the workflow of a web server
developed using Node.js.
Parts of Node js Architecture:
• Requests : Incoming requests can be blocking (complex) or non-blocking (simple),
depending upon the tasks that a user wants to perform in a web application
• Node.js server: Node.js server is a server-side platform that takes requests from
users, processes those requests, and returns responses to the corresponding users
• Event Queue: Event Queue in a Node.js server stores incoming client requests and
passes those requests one-by-one into the Event Loop
• Thread pool: Thread pool consists of all the threads available for carrying out some
tasks that might be required to fulfill client requests

By: Dr. Ami Desai 2


• Event loop: Event Loop indefinitely receives requests and processes them, and then
returns the responses to corresponding clients.
• External Resources: External resources are required to deal with blocking client
requests. These resources can be for computation, data storage, etc.
The workflow of Node js Architecture:

A web server developed using Node.js typically has a workflow that is quite similar to the
diagram illustrated below. Let’s explore this flow of operations in detail.
• Clients send requests to the webserver to interact with the web application. Requests
can be non-blocking or blocking e.g Querying the data , updating the data or deleting
the data .
• Node.js retrieves the incoming requests and adds those requests to the Event Queue.
• The requests are then passed one-by-one through the Event Loop. It checks if the
requests are simple enough to not require any external resources.
• Event Loop processes simple requests (non-blocking operations), such as I/O Polling,
and returns the responses to the corresponding clients.
• A single thread from the Thread Pool is assigned to a single complex request. This
thread is responsible for completing a particular blocking request by accessing the
external resources, such as compute, database, file system, etc.
Once, the task is carried out completely, the response is sent to the Event Loop that in turn
sends that response back to the Client.
Advantages of Node.js Architecture:
Node.js Architecture comes with several advantages that give the server-side platform a
distinct upper-hand when compared to other server-side languages:
• Handling multiple concurrent client requests is fast and easy: With the use of Event
Queue and Thread Pool, the Node.js server enables efficient handling of a large
number of incoming requests.
• No need for creating multiple threads: Event Loop handles all requests one-by-one,
so there is no need to create multiple threads. Instead, a single thread is sufficient to
handle a blocking incoming request.
All of these advantages contribute to making the servers developed using Node.js much faster
and responsive when compared to those developed using other server development
technologies.

By: Dr. Ami Desai 3


Install Node.js on a Webserver
Step 1: Download and install NodeJS
Use this google.com to download the latest version of Node.js and then install it on your local
machine using all the default options.
Step 2: Install the HTTP-server package from npm(node package manager)
You can run the Node.js application directly from a command prompt or a command-line
window. Now, you need to install the HTTP-server module, it should be installed as a global
npm package.
Open the command prompt/command line and enter the following command:
npm install -g http-server
Step 3: Start a web server from a directory containing static website Files
Now, after installing the module, you need to start the server. For that, you first need to change
to the directory containing your static web files (HTML/CSS/JS, etc). Use the cd command for
that.
In a command prompt/command line, enter the following command:
cd projects\node
Now, start the server with the following command:
http-server
Now, you will see the following output on screen:

Step 4: Browse to your local website with a browser


Open any browser and go to http://localhost:8080/ (URL which we get from as output after
we execute the above command). Now we can see our local website running, this is how we
can install Node.js on a web server.

Install Node.js for your platform/ Downloading Node.js


Step 1: Install Node.js for your platform (MacOS, Windows or Linux)

Go to goolge.come →nodejs.org→ https://nodejs.org/en/download -->click on windows


installer
After download install like game/application (next,finish)
2. Create folder in vscode / Open a command prompt and type:
mkdir myapp
cd myapp
or
For run program Node.js go to vscode(or any editor) create new folder/open existing folder

By: Dr. Ami Desai 4


3. Initialize your project and link it to npm : Npm is short for node package manager. This is
where all node packages live. Packages can be viewed as bundles of code, like modules
Running this command initializes your project:
npm init
This creates a package.json file in your myapp folder
You can enter your way through all of them EXCEPT this one:
entry point: (index.js)
You will want to change this to:
app.js
Note : Go to terminal write node –version
Nmp –version
if error than write
- Set-ExecutionPolicy -ExecutionPolicy Unrestricted -Scope Process
- Set-ExecutionPolicy -ExecutionPolicy Unrestricted -Scope Currentuser

4. Install Express in the myapp directory


While still in the myapp directory run:
npm install express --save
The install command will go ahead and find the package you wish to install, and install it to
your project. You will now be able to see a node_modules folder get created in the root of
your project. you will be able to require any of the recently installed files in your own
application files. The addition of —save will save the package to your dependencies list,
located in the package.json, in your myapp directory.
5. Start your text editor of choice and create a file named app.js.
Write
EXMAPLE 1: // Filename: index.js
// Filename: calc.js
exports.add = function (x, y) { const calculator = require('./calc');
return x + y;
}; let x = 50, y = 10;

exports.sub = function (x, y) { console.log("Addition of 50 and 10 is "


return x - y; + calculator.add(x, y));
};
console.log("Subtraction of 50 and 10 is "
exports.mult = function (x, y) { + calculator.sub(x, y));
return x * y;
}; console.log("Multiplication of 50 and 10 is "
+ calculator.mult(x, y));
exports.div = function (x, y) {
return x / y; console.log("Division of 50 and 10 is "
}; + calculator.div(x, y));

EXMAPLE 2:

const http = require('http');

By: Dr. Ami Desai 5


const hostname = '127.0.0.1';
const port = 8081;

const server = http.createServer((req, res) => {


res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World');
});

server.listen(port, hostname, () => {


console.log(`Server running at http://${hostname}:${port}/`);
});

6. Run the app


Type the command: node app.js

Components
Node.js includes several components for developing, testing, and deploying enterprise
applications. The primary components are
• Node CLI(command line interface)
• NPM
• package.json
• third-party modules such as Mongoose and MongoDB
• and Node Core modules such as http, url, querystring, and fs.

1. Node CLI (Command Line Interface)


The Node.js Command Line Interface (CLI) allows developers to run JavaScript files, execute
commands, and interact with the Node.js runtime directly from the terminal.
Example:
1. Open the terminal or command prompt.
2. Run the following command to check the installed Node.js version:
node -v
3. Execute a simple JavaScript file using Node.js:
node app.js

By: Dr. Ami Desai 6


2. NPM (Node Package Manager)
NPM is a package manager that comes with Node.js. It helps in installing, updating, and
managing JavaScript libraries (packages).
Example:
• To check the installed NPM version:
npm -v
• To install a package (e.g., Express):
npm install express
• To install a package globally:
npm install -g nodemon
3. package.json
package.json is a configuration file that contains metadata about a Node.js project,
including its dependencies, scripts, and settings.
Example: Creating a package.json file using NPM:
npm init -y
This generates a package.json file:
json
{
"name": "my-project",
"version": "1.0.0",
"description": "A sample Node.js project",
"dependencies": {
"express": "^4.17.1"
},
"scripts": {
"start": "node index.js"
}
}

4. Third-Party Modules (e.g., Mongoose and MongoDB)


These are external libraries that extend the functionality of Node.js.
• Mongoose: A library for MongoDB object modeling.
• MongoDB: A NoSQL database used with Node.js.
Example: Installing Mongoose:
npm install mongoose
Using Mongoose in a Node.js file:

const mongoose = require('mongoose');


mongoose.connect('mongodb://localhost:27017/mydatabase', { useNewUrlParser: true,
useUnifiedTopology: true });

5. Node Core Modules (e.g., http, url, querystring, and fs)


Node.js comes with built-in modules that provide various functionalities.
const http = require('http');
const url = require('url');
const fs = require('fs');

By: Dr. Ami Desai 7


const server = http.createServer((req, res) => {
const parsedUrl = url.parse(req.url, true);

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.
Module properties/method
1. exports: The object that a module can export for use in other modules.
2. require(): A function that is used to import modules into other modules.
3. module: The object that represents the current module.
Types of Node
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');

Important core modules in Node.js:


Modules Description
http creates an HTTP server in Node.js.
assert set of declaration 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
our Node.js application. These modules are included in our program in the same way as
we include the built in module.

Ex : //FileName : sum.js
exports.add=function(n,m){
return n+m;
};
Exports keyword is used to make properties and methods available outside the file.

In order to include the add function in our index.js file we use the require function.
Ex : let sum = require('./sum')

3) Third-party modules

By: Dr. Ami Desai 8


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
Ex:
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}`);
});

Create Server(http.createServer()):
Creating an HTTP server using http.createServer() in Node.js is a fundamental way to serve
requests and responses. The http module in Node.js provides this functionality
There are 3 steps
I. Import the http module: The http module is built into Node.js, so you don't need to
install it.
II. Create a server: Use http.createServer() to create a new server instance. The
function takes a callback that is executed each time the server receives a request.
III. Listen on a port: Use the server.listen() method to specify the port and hostname
the server will use.

// Step 1: Import the http module


const http = require('http');

// Step 2: Create the server


const server = http.createServer((req, res) => {
// req: Request object
// res: Response object

// Log the request method and URL


console.log(`Request method: ${req.method}, URL: ${req.url}`);

// Set the response header


res.writeHead(200, { 'Content-Type': 'text/plain' });

// Send a response
res.end('Hello, World! Welcome to my Node.js server.\n');

By: Dr. Ami Desai 9


});

// Step 3: Start the server and listen on a port


const PORT = 3000; // You can change the port number
const HOSTNAME = '127.0.0.1'; // localhost

server.listen(PORT, HOSTNAME, () => {


console.log(`Server is running at http://${HOSTNAME}:${PORT}/`);
});
Here,
1. http.createServer(callback):
• The callback takes two arguments: req (request object) and res (response object).
• req contains information about the HTTP request (e.g., URL, method, headers).
• res is used to send back the HTTP response.
2. res.writeHead(statusCode, headers):
• Sets the HTTP status code and headers for the response.
• Example: res.writeHead(200, { 'Content-Type': 'text/plain' });
3. res.end(data):
• Ends the response and sends data to the client.
4. server.listen(port, hostname, callback):
• Specifies the port and hostname where the server will listen for incoming requests.
• The callback is executed once the server starts listening.

Request and response


The Request and Response Process
When a Node.js server receives an HTTP request, it creates a stream for that request. As
data is received from the client, it is placed into a buffer, and once that buffer reaches a
certain size, it is sent along in a ‘data’ event.
Receiving Data (Request)
The request object in an HTTP server callback is a readable stream. Here’s a basic example of
how to read data from the request:
const http = require('http');

http.createServer((req, res) => { // Creates an HTTP server in Node.js


let body = [];
req.on('data', function(chunk) { // Captures incoming data chunks
// Each 'chunk' is a Buffer instance
body.push(chunk);
}).on('end', function(){ // Fires when all data is received
body = Buffer.concat(body).toString(); // Combines chunks and converts them to a string
// At this point, we have the complete request body
});
}).listen(8080);// Starts the server on port 8080
Sending Data (Response)
The response object is a writable stream. You can use the write method to send a response
back to the client in chunks. Here’s how you can write data to the response:

By: Dr. Ami Desai 10


const http = require('http');

http.createServer((req, res) => {


res.write('Hello, World!');
res.end(); // End the response
}).listen(8080);

Node.js as Web-server:
Node.js allows developers to use JavaScript to write back-end code, even though traditionally
it was used in the browser to write front-end code. Having both the frontend and backend
together like this reduces the effort it takes to make a web server, which is a major reason why
Node.js is a popular choice for writing back-end code.

Node JS Require Module


Use the require() function to load built-in modules. It is use with all type of module. But way
may be different

Example
Module Type How to Import Installation
Module
Built-in Module http, fs const fs = require('fs'); No
Yes (npm install
Third-party Module Lodash const _ = require('lodash');
lodash)
const math =
Custom Module math.js No
require('./math');

Ex:
const fs = require('fs');

// Write a file
fs.writeFileSync('example.txt', 'Hello, Node.js!');
console.log('File created.');

// Read the file


const data = fs.readFileSync('example.txt', 'utf8');
console.log(`File content: ${data}`);

▪ Each JavaScript file(JS) is treated as a separate module in NodeJS.


▪ It uses commonJS module system: require(), exports and module.export.
▪ The main object exported by require() module is a function.
▪ require() is used to consume modules. It allows us to include modules in our current
application.
▪ When Node invokes that require() function with a file path as the function’s only
argument, Node goes through the following sequence of steps:

By: Dr. Ami Desai 11


1. Resolving and Loading:
▪ In this step, NodeJS decides which module to load core module or developer module
or 3rd-party module using the following steps:
o When require function receive the module name as its input, It first tries to
load core module.
o `If path in require function begins with ‘./’ or ‘../’ It will try to load developer
module. Example: require(‘./sum’);
o If no file is find, it will try to find folder with index.js in it .
o Else it will go to node_modules/ and try to load module from here.
o If file is still not found, then an error is thrown .
2. Wrapping:
▪ Once the module is loaded, the module code is wrapped in a special function which
will give access to a couple of objects.

3. Execution:
▪ In this part, the code of the module or code inside the wrapper function is run or
executed by the NodeJS runtime.
4. Returning Exports:
▪ In this part, require function returns the exports of required module. These exports
are stored in module.exports.
▪ Use module.exports to export single variable/class/function. If you want to export
multiple function or variables use exports ( exports.add = (a,b)=>a+b ).
5. Caching:
▪ At the end all modules are cached after the first time they are loaded.
▪ E.g. If we require the same module multiple times, we will get the same result. So
the code and modules are executed in the first call and in a subsequent call, results
are retrieved from the cache.

createServer()
The http.createServer() method turns your computer into an HTTP server. The
http.createServer() method creates an HTTP Server object. The HTTP Server object can listen

By: Dr. Ami Desai 12


to ports on your computer and execute a function, a requestListener, each time a request is
made.
The createServer method creates a server on your computer.
Syntax:
http.createServer(requestListener);

requestListener : Optional. Specifies a function to be executed every time the server gets
a request. This function is called a requestListener, and handles request from the user, as well
as response back to the user.
The function passed in the http.createServer() will be executed when the client goes to the
url http://localhost:8081.
▪ Steps to run the code:
o Save the above code in a file with .js extension
o Open the command prompt and go to the folder where the file is there
using cd command.
o Run the command node file_name.js
o Open the browser and go the url http://localhost:8081
▪ The http.createServer() method includes request object that can be used to get
information about the current HTTP request e.g. url, request header, and data.

index.js
const http = require('http');

const hostname = '127.0.0.1';


const port = 8081;

const server = http.createServer((req, res) => {


res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World, I\'m Gaurang Joshi');
});

server.listen(port, hostname, () => {


console.log(`Server running at
http://${hostname}:${port}/`);
});
▪ The value localhost is a special private address that computers use to refer to
themselves. It’s typically the equivalent of the internal IP address 127.0.0.1 and it’s
only available to the local computer, not to any local networks we’ve joined or to the
internet.
▪ The port is a number that servers use as an endpoint or “door” to our IP address. In
our example, we will use port 8081 for our web server. Ports 8080 and 8000 are

By: Dr. Ami Desai 13


typically used as default ports in development, and in most cases developers will use
them rather than other ports for HTTP servers.
▪ When we bind our server to this host and port, we will be able to reach our server by
visiting http://localhost:8081 in a local browser.
▪ We add a special function, which in Node.js we call a request listener. This function is
meant to handle an incoming HTTP request and return an HTTP response. This
function must have two arguments, a request object and a response object. The
request object captures all the data of the HTTP request that’s coming in. The
response object is used to return HTTP responses from the server.

Read the Query String


The function in the createServer() has a request argument and this request object has a
property of URL. It contains the part of the url that is present after the domain name. So
when you go to localhost:3000/TMTBCA/nodejs, the output will be TMTBCA/nodejs
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.write(req.url);
res.end();
}).listen(3000);

Split the Query String


This is a built-in module of node.js. It breaks down the url into readable parts. It is included
in the file by using the require() function;
To Parse an address, use the url.parse() method. It will return a URL object with each part of
the address as its properties.
var http = require('http');
var url = require('url');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
var q = url.parse(req.url, true).query; //true return object
var txt = q.year + " " + q.month;
res.end(txt);
}).listen(8080);
Ex 2 :
var url = require('url');
var adr = 'http://localhost:8080/default.htm?year=2017&month=february';
var q = url.parse(adr, true);
console.log(q.host); //returns 'localhost:8080'
console.log(q.pathname); //returns '/default.htm'
console.log(q.search); //returns '?year=2017&month=february'

By: Dr. Ami Desai 14


var qdata = q.query; //returns an object: { year: 2017, month: 'february' }
console.log(qdata.month); //returns 'february'

Node.js File System module:


Node.js includes fs module to access physical file system. The fs module is responsible for all
the asynchronous or synchronous file I/O operations. It helps to create, read, write, update,
or delete files in our computer. It is included in the file by using the require() function.
Common use for the File System module:
• Read files
• Create files
• Update files
• Delete files
• Rename files

Reading File
Use the fs.readFile() method to read the physical file asynchronously.
Syntax : fs.readFile(fileName [,options], callback)
Ex : 1
var fs = require('fs');
fs.readFile('Demo.txt', 'uft-8' ,function (err, file) {
if (err) throw err;
console.log('Saved!');
});

Ex: 2 File: DataHtml.html

<html>
<body>
<h1>My Header</h1>
<p>My <b>Fantastic</b> paragraph.</p>
</body>
</html>

By: Dr. Ami Desai 15


File: DataHtml.html

var http = require('http');

var fs = require('fs');
http.createServer(function (req, res) {
fs.readFile('DataHtml.html', function(err, data) {
res.writeHead(200, {'Content-Type':'text/html'});
res.write(data);
return res.end();
});
}).listen(8080);

Use the fs.readFileSync() method to read file synchronously


Create Files
The File System module has methods for creating new files:

▪ fs.appendFile()
▪ fs.open()
▪ fs.writeFile()

1) fs.appendFile()

The fs.appendFile() method appends specified content to a file. If the file does not exist,
the file will be created:
var fs = require('fs');

fs.appendFile('MyData1.txt', 'Hello World!', function (err) {


if (err) throw err;
console.log('Saved!');
});

2) fs.open()
The fs.open() method takes a "flag" as the second argument, if the flag is "w" for
"writing", the specified file is opened for writing. If the file does not exist, an empty file
is created:

Syntax : fs.open(path, flags[, mode], callback)

By: Dr. Ami Desai 16


var fs = require('fs');

fs.open('MyData2.txt', 'w', function (err, file) {


if (err) throw err;
console.log('Saved!');
});

The following table lists all the flags which can be used in read/write operation.
Flag Description
R Open file for reading. An exception occurs if the file does not exist.
r+ Open file for reading and writing. An exception occurs if the file does not exist.
Rs Open file for reading in synchronous mode.
rs+ Open file for reading and writing, telling the OS to open it synchronously. See notes for 'rs' about
using this with caution.
W Open file for writing. The file is created (if it does not exist) or truncated (if it exists).
Wx Like 'w' but fails if path exists.
w+ Open file for reading and writing. The file is created (if it does not exist) or truncated (if it exists).
wx+ Like 'w+' but fails if path exists.
A Open file for appending. The file is created if it does not exist.
Ax Like 'a' but fails if path exists.
a+ Open file for reading and appending. The file is created if it does not exist.
ax+ Like 'a+' but fails if path exists.

3) fs.writeFile()

The fs.writeFile() method replaces the specified file and content if it exists. If the file
does not exist, a new file, containing the specified content, will be created:

var fs = require('fs');

fs.writeFile('MyData3.txt', 'Hello content!', function (err) {


if (err) throw err;
console.log('Saved!');
});

Update files
The File System module has methods for updating files:

• fs.appendFile()
• fs.writeFile()

1) The fs.appendFile() method appends the specified content at the end of the specified file:

var fs = require('fs');

fs.appendFile('MyData1.txt', ' This is my text.', function (err) {


if (err) throw err;

By: Dr. Ami Desai 17


console.log('Updated!');
});

2) The fs.writeFile() method replaces the specified file and content:

var fs = require('fs');

fs.writeFile('MyData2.txt', 'This is my text', function (err) {


if (err) throw err;
console.log('Replaced!');
});

Delete files
To delete a file with the File System module, use the fs.unlink() method. The fs.unlink()
method deletes the specified file:
var fs = require('fs');

fs.unlink('MyData1.txt', function (err) {


if (err) throw err;
console.log('File deleted!');
});

Rename files
To rename a file with the File System module, use the fs.rename() method. The fs.rename()
method renames the specified file:

var fs = require('fs');

fs.rename('MyData2.txt', 'MyNewFile.txt', function (err) {


if (err) throw err;
console.log('File Renamed!');
});

By: Dr. Ami Desai 18

You might also like