SlideShare une entreprise Scribd logo
1  sur  17
CH 6: FILE SYSTEM
Prepared By: Bareen Shaikh
Common use for the File System
module
 Read files:
fs.readFile()
fs.readFileSync()
 Create files:
fs.open()
fs.writeFile()
 Update files:
fs.appendFile()
fs.writeFile()
 Delete files:
fs.unlink()
 Rename files:
fs.rename()
Creating a file: fs.open()
 fs.open() method does several operations on a file.
 Syntax:
fs.open( filename, flags, mode, callback )
 Parameter: This method accept four parameters as
below:
 filename: It holds the name of the file to read or the entire
path if stored at other location.
 flag: The operation in which file has to be opened.
 mode: Sets the mode of file i.e. r-read, w-write, r+ -
readwrite. It sets to default as readwrite.
 callback: It is a callback function that is called after reading
a file. It takes two parameters:
 err: If any error occurs.
Flags of fs.open()
 All the types of flags are described below:
 r: To open file to read and throws exception if file doesn’t
exists.
 r+: Open file to read and write. Throws exception if file
doesn’t exists
 rs+: Open file in synchronous mode to read and write.
 w: Open file for writing. File is created if it doesn’t exists.
 wx: It is same as ‘w’ but fails if path exists.
 w+: Open file to read and write. File is created if it doesn’t
exists.
 wx+: It is same as ‘w+’ but fails if path exists.
 a: Open file to append. File is created if it doesn’t exists.
 ax: It is same as ‘a’ but fails if path exists.
 a+: Open file for reading and appending. File is created if it
doesn’t exists.
Example of : fs.open()
var fs = require('fs');
// Open file a.txt in read mode
fs.open(‘a.txt', 'r', function (err, data) {
console.log(data);
console.log('Saved!');
});
Reading a file: fs.readFile()
 The fs.readFile() method is an inbuilt method which is
used to read the file. This method read the entire file
into buffer.
 Using fs.readFile() method, file can be read in a non-
blocking asynchronous way.
 Syntax:
fs.readFile( filename, encoding, callback_function )
Parameters: The method accept three parameters as
below:
 filename: It holds the name of the file to read or the entire
path if stored at other location.
 encoding: It holds the encoding of file. Its default value
is ‘utf8’.
 callback function: It is a callback function that is called
after reading of file. It takes two parameters:
Example
var http = require('http');
var fs = require('fs');
http.createServer(function (req, res) {
fs.readFile(‘app.js', function(err, data) {
if(err)
console.log(err);
else
{
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
res.end();
}
});
}).listen(8080);
Reading File: fs.readFileSync()
 The fs.readFileSync() method is an inbuilt application
programming interface of fs module which is used to
read the file and return its content.
 fs.readFileSync() method, read files in a synchronous
way, i.e. we are telling node.js to block other parallel
process and do the current file reading process.
 When the fs.readFileSync() method is called
 The original node program stops executing
 Executing node waits for the fs.readFileSync() function to
get executed
 After completion of the fs.readFileSync() method the
remaining node program is executed.
Syntax of fs.readFileSync()
 Syntax:
fs.readFileSync( path, options )
 Parameters:
 path: It takes the relative path of the text file. The path can
be of URL type.
 options: It is an optional parameter which contains the
encoding and flag, the encoding contains data specification.
It’s default value is null which returns raw buffer and the flag
contains indication of operations in the file. It’s default value
is ‘r’.
 Example:
const fs = require('fs');
const data = fs.readFileSync(‘app.js',
{encoding:'utf8',
flag:'r'});
Example of fs.readFile() &
fs.readFileSync()
const fs = require('fs');
// Calling the fs.readFile() method for reading file
fs.readFile(‘a.txt', {encoding:'utf8', flag:'r'}, function(err,
data) {
if(err)
console.log(err);
else
console.log(data);
});
// Calling the fs.readFileSync() method for reading file
‘b.txt'
const data = fs.readFileSync(‘b.txt', {encoding:'utf8',
flag:'r'});
Writing to a File: fs.writeFile()
 The fs.writeFile() method is used to asynchronously write the specified data to a file.
 The file would be replaced if it ex
 Syntax:
fs.writeFile( file, data, options, callback )
 Parameters: This method accept four parameters as mentioned above and described
below:
 file: It is a string denotes the path of the file where it has to be written.
 data: It is a string, Buffer, TypedArray or DataView that will be written to the file.
 options: It is an string or object that can be used to specify optional parameters
that will affect the output. It has three optional parameter:
encoding: It is a string value that specifies the encoding of the file. The default
value is ‘utf8’.
mode: It is an integer value that specifies the file mode. The default value is 0o666.
flag: It is a string value that specifies the flag used while writing to the file. The
default value is ‘w’.
 callback: It is the function that would be called when the method is executed.
Example of fs.writeFile()
const fs = require('fs');
let data =
"This is a file containing a a data n1111n 2222n 3333";
fs.writeFile(“a.txt", data, (err) => {
if (err)
console.log(err);
else {
console.log("File written successfullyn");
console.log("The written has the following contents:");
console.log(fs.readFileSync(“a.txt", "utf8"));
}
});
Writing to a File: fs.writeFileSync()
 The fs.writeFileSync() is a synchronous method.
 The fs.writeFileSync() creates a new file if the specified file does not
exist.
 Syntax:
fs.writeFileSync( file, data, options )
 Parameters: This method accept three parameters as follows:
file: It is a string, that denotes the path of the file where it has to be
written.
data: It is a string, Buffer, TypedArray or DataView that will be written
to the file.
options: It is an string or object that can be used to specify optional
parameters that will affect the output. It has three optional parameter:
 encoding: It is a string which specifies the encoding of the file. The
default value is ‘utf8’.
 mode: It is an integer which specifies the file mode. The default value is
0o666.
 flag: It is a string which specifies the flag used while writing to the file.
Example of fs.writeFileSync()
const fs = require('fs');
let data = "This is a file containing a collection"
+ " of programming languages.n"
+ "1. Cn2. C++n3. Python";
fs.writeFileSync(“programming.txt", data);
console.log("File written successfullyn");
console.log("The written has the following contents:");
console.log(fs.readFileSync("programming.txt",
"utf8"));
Appending to file fs.appendFile()
 fs.appendFile() method is used to asynchronously append the given data to a
file.
 A new file is created if it does not exist.
 Syntax
fs.appendFile( path, data[, options], callback)
 Parameters: This method accepts four parameters as mentioned above and
described below:
path: It is a String, Buffer, URL or number that denotes the source filename or file
descriptor that will be appended to.
data: It is a String or Buffer that denotes the data that has to be appended.
options: It is an string or an object that can be used to specify optional
parameters that will affect the output. It has three optional parameters:
 encoding: It is a string which specifies the encoding of the file. The default
value is ‘utf8’.
 mode: It is an integer which specifies the file mode. The default value is
‘0o666’.
 flag: It is a string which specifies the flag used while appending to the file. The
default value is ‘a’.
callback: It is a function that would be called when the method is executed.
Appending to file fs.appendFile()
const fs = require('fs');
// Get the file contents before the append operation
console.log("nFile Contents of file before append:",
var data=fs.readFileSync(“programming.txt”,{})
fs.readFileSync("example_file.txt", "utf8"));
fs.appendFile("example_file.txt", data, (err) => {
if (err) {
console.log(err);
}
else {
// Get the file contents after the append operation
console.log("nFile Contents of file after append:“),
console.log(fs.readFileSync("example_file.txt", "utf8"));
}
});
Var fs=require(‘fs’)
 Open
 fs.open()
 Write
 fs.writeFileSync()
 fs.writeFile()
 Reading
 fs.readFileSync()
 fs.readFile()
 Append
 fs.appenFile() //asyn

Contenu connexe

Tendances

React Router: React Meetup XXL
React Router: React Meetup XXLReact Router: React Meetup XXL
React Router: React Meetup XXLRob Gietema
 
Java 8-streams-collectors-patterns
Java 8-streams-collectors-patternsJava 8-streams-collectors-patterns
Java 8-streams-collectors-patternsJosé Paumard
 
REST APIs with Spring
REST APIs with SpringREST APIs with Spring
REST APIs with SpringJoshua Long
 
Spring boot - an introduction
Spring boot - an introductionSpring boot - an introduction
Spring boot - an introductionJonathan Holloway
 
Node.js Express
Node.js  ExpressNode.js  Express
Node.js ExpressEyal Vardi
 
Basic Concept of Node.js & NPM
Basic Concept of Node.js & NPMBasic Concept of Node.js & NPM
Basic Concept of Node.js & NPMBhargav Anadkat
 
ES6 presentation
ES6 presentationES6 presentation
ES6 presentationritika1
 
Node js overview
Node js overviewNode js overview
Node js overviewEyal Vardi
 
Avoiding callback hell in Node js using promises
Avoiding callback hell in Node js using promisesAvoiding callback hell in Node js using promises
Avoiding callback hell in Node js using promisesAnkit Agarwal
 
ASP.NET Core MVC with EF Core code first
ASP.NET Core MVC with EF Core code firstASP.NET Core MVC with EF Core code first
ASP.NET Core MVC with EF Core code firstMd. Aftab Uddin Kajal
 
Asp.Net Core MVC with Entity Framework
Asp.Net Core MVC with Entity FrameworkAsp.Net Core MVC with Entity Framework
Asp.Net Core MVC with Entity FrameworkShravan A
 

Tendances (20)

Expressjs
ExpressjsExpressjs
Expressjs
 
React Router: React Meetup XXL
React Router: React Meetup XXLReact Router: React Meetup XXL
React Router: React Meetup XXL
 
Uploading a file with php
Uploading a file with phpUploading a file with php
Uploading a file with php
 
Java 8-streams-collectors-patterns
Java 8-streams-collectors-patternsJava 8-streams-collectors-patterns
Java 8-streams-collectors-patterns
 
REST APIs with Spring
REST APIs with SpringREST APIs with Spring
REST APIs with Spring
 
Php introduction
Php introductionPhp introduction
Php introduction
 
Intro to React
Intro to ReactIntro to React
Intro to React
 
Express js
Express jsExpress js
Express js
 
Spring boot - an introduction
Spring boot - an introductionSpring boot - an introduction
Spring boot - an introduction
 
Node.js Express
Node.js  ExpressNode.js  Express
Node.js Express
 
Java 8 Lambda and Streams
Java 8 Lambda and StreamsJava 8 Lambda and Streams
Java 8 Lambda and Streams
 
PHP - Introduction to PHP Cookies and Sessions
PHP - Introduction to PHP Cookies and SessionsPHP - Introduction to PHP Cookies and Sessions
PHP - Introduction to PHP Cookies and Sessions
 
Basic Concept of Node.js & NPM
Basic Concept of Node.js & NPMBasic Concept of Node.js & NPM
Basic Concept of Node.js & NPM
 
ES6 presentation
ES6 presentationES6 presentation
ES6 presentation
 
Node js overview
Node js overviewNode js overview
Node js overview
 
Avoiding callback hell in Node js using promises
Avoiding callback hell in Node js using promisesAvoiding callback hell in Node js using promises
Avoiding callback hell in Node js using promises
 
Java 8 Workshop
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
 
Sequelize
SequelizeSequelize
Sequelize
 
ASP.NET Core MVC with EF Core code first
ASP.NET Core MVC with EF Core code firstASP.NET Core MVC with EF Core code first
ASP.NET Core MVC with EF Core code first
 
Asp.Net Core MVC with Entity Framework
Asp.Net Core MVC with Entity FrameworkAsp.Net Core MVC with Entity Framework
Asp.Net Core MVC with Entity Framework
 

Similaire à FS_module_functions.pptx

Similaire à FS_module_functions.pptx (20)

Files nts
Files ntsFiles nts
Files nts
 
Php files
Php filesPhp files
Php files
 
File handling
File handlingFile handling
File handling
 
FILES IN C
FILES IN CFILES IN C
FILES IN C
 
Tutorial on Node File System
Tutorial on Node File SystemTutorial on Node File System
Tutorial on Node File System
 
Unit 8
Unit 8Unit 8
Unit 8
 
Understanding c file handling functions with examples
Understanding c file handling functions with examplesUnderstanding c file handling functions with examples
Understanding c file handling functions with examples
 
Unit-VI.pptx
Unit-VI.pptxUnit-VI.pptx
Unit-VI.pptx
 
file handling1
file handling1file handling1
file handling1
 
C Programming Unit-5
C Programming Unit-5C Programming Unit-5
C Programming Unit-5
 
INput output stream in ccP Full Detail.pptx
INput output stream in ccP Full Detail.pptxINput output stream in ccP Full Detail.pptx
INput output stream in ccP Full Detail.pptx
 
Unix-module3.pptx
Unix-module3.pptxUnix-module3.pptx
Unix-module3.pptx
 
File Organization
File OrganizationFile Organization
File Organization
 
Advance C Programming UNIT 4-FILE HANDLING IN C.pdf
Advance C Programming UNIT 4-FILE HANDLING IN C.pdfAdvance C Programming UNIT 4-FILE HANDLING IN C.pdf
Advance C Programming UNIT 4-FILE HANDLING IN C.pdf
 
file_handling_in_c.ppt
file_handling_in_c.pptfile_handling_in_c.ppt
file_handling_in_c.ppt
 
File handling-c
File handling-cFile handling-c
File handling-c
 
File handling in c
File handling in cFile handling in c
File handling in c
 
File handling in c
File handling in cFile handling in c
File handling in c
 
File handling
File handlingFile handling
File handling
 
C++17 std::filesystem - Overview
C++17 std::filesystem - OverviewC++17 std::filesystem - Overview
C++17 std::filesystem - Overview
 

Plus de Bareen Shaikh

Plus de Bareen Shaikh (11)

Express Generator.pdf
Express Generator.pdfExpress Generator.pdf
Express Generator.pdf
 
Middleware.pdf
Middleware.pdfMiddleware.pdf
Middleware.pdf
 
ExpressJS-Introduction.pdf
ExpressJS-Introduction.pdfExpressJS-Introduction.pdf
ExpressJS-Introduction.pdf
 
Express JS-Routingmethod.pdf
Express JS-Routingmethod.pdfExpress JS-Routingmethod.pdf
Express JS-Routingmethod.pdf
 
File System.pptx
File System.pptxFile System.pptx
File System.pptx
 
Web Server.pdf
Web Server.pdfWeb Server.pdf
Web Server.pdf
 
NPM.pdf
NPM.pdfNPM.pdf
NPM.pdf
 
NodeJs Modules1.pdf
NodeJs Modules1.pdfNodeJs Modules1.pdf
NodeJs Modules1.pdf
 
NodeJs Modules.pdf
NodeJs Modules.pdfNodeJs Modules.pdf
NodeJs Modules.pdf
 
Introduction to Node JS1.pdf
Introduction to Node JS1.pdfIntroduction to Node JS1.pdf
Introduction to Node JS1.pdf
 
Introduction to Node JS.pdf
Introduction to Node JS.pdfIntroduction to Node JS.pdf
Introduction to Node JS.pdf
 

Dernier

Keep Your Finger on the Pulse of Your Building's Performance with IES Live
Keep Your Finger on the Pulse of Your Building's Performance with IES LiveKeep Your Finger on the Pulse of Your Building's Performance with IES Live
Keep Your Finger on the Pulse of Your Building's Performance with IES LiveIES VE
 
Q4 2023 Quarterly Investor Presentation - FINAL - v1.pdf
Q4 2023 Quarterly Investor Presentation - FINAL - v1.pdfQ4 2023 Quarterly Investor Presentation - FINAL - v1.pdf
Q4 2023 Quarterly Investor Presentation - FINAL - v1.pdfTejal81
 
Planetek Italia Srl - Corporate Profile Brochure
Planetek Italia Srl - Corporate Profile BrochurePlanetek Italia Srl - Corporate Profile Brochure
Planetek Italia Srl - Corporate Profile BrochurePlanetek Italia Srl
 
UiPath Studio Web workshop Series - Day 3
UiPath Studio Web workshop Series - Day 3UiPath Studio Web workshop Series - Day 3
UiPath Studio Web workshop Series - Day 3DianaGray10
 
.NET 8 ChatBot with Azure OpenAI Services.pptx
.NET 8 ChatBot with Azure OpenAI Services.pptx.NET 8 ChatBot with Azure OpenAI Services.pptx
.NET 8 ChatBot with Azure OpenAI Services.pptxHansamali Gamage
 
The Importance of Indoor Air Quality (English)
The Importance of Indoor Air Quality (English)The Importance of Indoor Air Quality (English)
The Importance of Indoor Air Quality (English)IES VE
 
IT Service Management (ITSM) Best Practices for Advanced Computing
IT Service Management (ITSM) Best Practices for Advanced ComputingIT Service Management (ITSM) Best Practices for Advanced Computing
IT Service Management (ITSM) Best Practices for Advanced ComputingMAGNIntelligence
 
Extra-120324-Visite-Entreprise-icare.pdf
Extra-120324-Visite-Entreprise-icare.pdfExtra-120324-Visite-Entreprise-icare.pdf
Extra-120324-Visite-Entreprise-icare.pdfInfopole1
 
Outage Analysis: March 5th/6th 2024 Meta, Comcast, and LinkedIn
Outage Analysis: March 5th/6th 2024 Meta, Comcast, and LinkedInOutage Analysis: March 5th/6th 2024 Meta, Comcast, and LinkedIn
Outage Analysis: March 5th/6th 2024 Meta, Comcast, and LinkedInThousandEyes
 
The Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and InsightThe Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and InsightSafe Software
 
Novo Nordisk's journey in developing an open-source application on Neo4j
Novo Nordisk's journey in developing an open-source application on Neo4jNovo Nordisk's journey in developing an open-source application on Neo4j
Novo Nordisk's journey in developing an open-source application on Neo4jNeo4j
 
My key hands-on projects in Quantum, and QAI
My key hands-on projects in Quantum, and QAIMy key hands-on projects in Quantum, and QAI
My key hands-on projects in Quantum, and QAIVijayananda Mohire
 
Oracle Database 23c Security New Features.pptx
Oracle Database 23c Security New Features.pptxOracle Database 23c Security New Features.pptx
Oracle Database 23c Security New Features.pptxSatishbabu Gunukula
 
Design and Modeling for MySQL SCALE 21X Pasadena, CA Mar 2024
Design and Modeling for MySQL SCALE 21X Pasadena, CA Mar 2024Design and Modeling for MySQL SCALE 21X Pasadena, CA Mar 2024
Design and Modeling for MySQL SCALE 21X Pasadena, CA Mar 2024Alkin Tezuysal
 
UiPath Studio Web workshop series - Day 1
UiPath Studio Web workshop series  - Day 1UiPath Studio Web workshop series  - Day 1
UiPath Studio Web workshop series - Day 1DianaGray10
 
How to release an Open Source Dataweave Library
How to release an Open Source Dataweave LibraryHow to release an Open Source Dataweave Library
How to release an Open Source Dataweave Libraryshyamraj55
 
LF Energy Webinar - Unveiling OpenEEMeter 4.0
LF Energy Webinar - Unveiling OpenEEMeter 4.0LF Energy Webinar - Unveiling OpenEEMeter 4.0
LF Energy Webinar - Unveiling OpenEEMeter 4.0DanBrown980551
 
Introduction to RAG (Retrieval Augmented Generation) and its application
Introduction to RAG (Retrieval Augmented Generation) and its applicationIntroduction to RAG (Retrieval Augmented Generation) and its application
Introduction to RAG (Retrieval Augmented Generation) and its applicationKnoldus Inc.
 
Technical SEO for Improved Accessibility WTS FEST
Technical SEO for Improved Accessibility  WTS FESTTechnical SEO for Improved Accessibility  WTS FEST
Technical SEO for Improved Accessibility WTS FESTBillieHyde
 
2024.03.12 Cost drivers of cultivated meat production.pdf
2024.03.12 Cost drivers of cultivated meat production.pdf2024.03.12 Cost drivers of cultivated meat production.pdf
2024.03.12 Cost drivers of cultivated meat production.pdfThe Good Food Institute
 

Dernier (20)

Keep Your Finger on the Pulse of Your Building's Performance with IES Live
Keep Your Finger on the Pulse of Your Building's Performance with IES LiveKeep Your Finger on the Pulse of Your Building's Performance with IES Live
Keep Your Finger on the Pulse of Your Building's Performance with IES Live
 
Q4 2023 Quarterly Investor Presentation - FINAL - v1.pdf
Q4 2023 Quarterly Investor Presentation - FINAL - v1.pdfQ4 2023 Quarterly Investor Presentation - FINAL - v1.pdf
Q4 2023 Quarterly Investor Presentation - FINAL - v1.pdf
 
Planetek Italia Srl - Corporate Profile Brochure
Planetek Italia Srl - Corporate Profile BrochurePlanetek Italia Srl - Corporate Profile Brochure
Planetek Italia Srl - Corporate Profile Brochure
 
UiPath Studio Web workshop Series - Day 3
UiPath Studio Web workshop Series - Day 3UiPath Studio Web workshop Series - Day 3
UiPath Studio Web workshop Series - Day 3
 
.NET 8 ChatBot with Azure OpenAI Services.pptx
.NET 8 ChatBot with Azure OpenAI Services.pptx.NET 8 ChatBot with Azure OpenAI Services.pptx
.NET 8 ChatBot with Azure OpenAI Services.pptx
 
The Importance of Indoor Air Quality (English)
The Importance of Indoor Air Quality (English)The Importance of Indoor Air Quality (English)
The Importance of Indoor Air Quality (English)
 
IT Service Management (ITSM) Best Practices for Advanced Computing
IT Service Management (ITSM) Best Practices for Advanced ComputingIT Service Management (ITSM) Best Practices for Advanced Computing
IT Service Management (ITSM) Best Practices for Advanced Computing
 
Extra-120324-Visite-Entreprise-icare.pdf
Extra-120324-Visite-Entreprise-icare.pdfExtra-120324-Visite-Entreprise-icare.pdf
Extra-120324-Visite-Entreprise-icare.pdf
 
Outage Analysis: March 5th/6th 2024 Meta, Comcast, and LinkedIn
Outage Analysis: March 5th/6th 2024 Meta, Comcast, and LinkedInOutage Analysis: March 5th/6th 2024 Meta, Comcast, and LinkedIn
Outage Analysis: March 5th/6th 2024 Meta, Comcast, and LinkedIn
 
The Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and InsightThe Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and Insight
 
Novo Nordisk's journey in developing an open-source application on Neo4j
Novo Nordisk's journey in developing an open-source application on Neo4jNovo Nordisk's journey in developing an open-source application on Neo4j
Novo Nordisk's journey in developing an open-source application on Neo4j
 
My key hands-on projects in Quantum, and QAI
My key hands-on projects in Quantum, and QAIMy key hands-on projects in Quantum, and QAI
My key hands-on projects in Quantum, and QAI
 
Oracle Database 23c Security New Features.pptx
Oracle Database 23c Security New Features.pptxOracle Database 23c Security New Features.pptx
Oracle Database 23c Security New Features.pptx
 
Design and Modeling for MySQL SCALE 21X Pasadena, CA Mar 2024
Design and Modeling for MySQL SCALE 21X Pasadena, CA Mar 2024Design and Modeling for MySQL SCALE 21X Pasadena, CA Mar 2024
Design and Modeling for MySQL SCALE 21X Pasadena, CA Mar 2024
 
UiPath Studio Web workshop series - Day 1
UiPath Studio Web workshop series  - Day 1UiPath Studio Web workshop series  - Day 1
UiPath Studio Web workshop series - Day 1
 
How to release an Open Source Dataweave Library
How to release an Open Source Dataweave LibraryHow to release an Open Source Dataweave Library
How to release an Open Source Dataweave Library
 
LF Energy Webinar - Unveiling OpenEEMeter 4.0
LF Energy Webinar - Unveiling OpenEEMeter 4.0LF Energy Webinar - Unveiling OpenEEMeter 4.0
LF Energy Webinar - Unveiling OpenEEMeter 4.0
 
Introduction to RAG (Retrieval Augmented Generation) and its application
Introduction to RAG (Retrieval Augmented Generation) and its applicationIntroduction to RAG (Retrieval Augmented Generation) and its application
Introduction to RAG (Retrieval Augmented Generation) and its application
 
Technical SEO for Improved Accessibility WTS FEST
Technical SEO for Improved Accessibility  WTS FESTTechnical SEO for Improved Accessibility  WTS FEST
Technical SEO for Improved Accessibility WTS FEST
 
2024.03.12 Cost drivers of cultivated meat production.pdf
2024.03.12 Cost drivers of cultivated meat production.pdf2024.03.12 Cost drivers of cultivated meat production.pdf
2024.03.12 Cost drivers of cultivated meat production.pdf
 

FS_module_functions.pptx

  • 1. CH 6: FILE SYSTEM Prepared By: Bareen Shaikh
  • 2. Common use for the File System module  Read files: fs.readFile() fs.readFileSync()  Create files: fs.open() fs.writeFile()  Update files: fs.appendFile() fs.writeFile()  Delete files: fs.unlink()  Rename files: fs.rename()
  • 3. Creating a file: fs.open()  fs.open() method does several operations on a file.  Syntax: fs.open( filename, flags, mode, callback )  Parameter: This method accept four parameters as below:  filename: It holds the name of the file to read or the entire path if stored at other location.  flag: The operation in which file has to be opened.  mode: Sets the mode of file i.e. r-read, w-write, r+ - readwrite. It sets to default as readwrite.  callback: It is a callback function that is called after reading a file. It takes two parameters:  err: If any error occurs.
  • 4. Flags of fs.open()  All the types of flags are described below:  r: To open file to read and throws exception if file doesn’t exists.  r+: Open file to read and write. Throws exception if file doesn’t exists  rs+: Open file in synchronous mode to read and write.  w: Open file for writing. File is created if it doesn’t exists.  wx: It is same as ‘w’ but fails if path exists.  w+: Open file to read and write. File is created if it doesn’t exists.  wx+: It is same as ‘w+’ but fails if path exists.  a: Open file to append. File is created if it doesn’t exists.  ax: It is same as ‘a’ but fails if path exists.  a+: Open file for reading and appending. File is created if it doesn’t exists.
  • 5. Example of : fs.open() var fs = require('fs'); // Open file a.txt in read mode fs.open(‘a.txt', 'r', function (err, data) { console.log(data); console.log('Saved!'); });
  • 6. Reading a file: fs.readFile()  The fs.readFile() method is an inbuilt method which is used to read the file. This method read the entire file into buffer.  Using fs.readFile() method, file can be read in a non- blocking asynchronous way.  Syntax: fs.readFile( filename, encoding, callback_function ) Parameters: The method accept three parameters as below:  filename: It holds the name of the file to read or the entire path if stored at other location.  encoding: It holds the encoding of file. Its default value is ‘utf8’.  callback function: It is a callback function that is called after reading of file. It takes two parameters:
  • 7. Example var http = require('http'); var fs = require('fs'); http.createServer(function (req, res) { fs.readFile(‘app.js', function(err, data) { if(err) console.log(err); else { res.writeHead(200, {'Content-Type': 'text/html'}); res.write(data); res.end(); } }); }).listen(8080);
  • 8. Reading File: fs.readFileSync()  The fs.readFileSync() method is an inbuilt application programming interface of fs module which is used to read the file and return its content.  fs.readFileSync() method, read files in a synchronous way, i.e. we are telling node.js to block other parallel process and do the current file reading process.  When the fs.readFileSync() method is called  The original node program stops executing  Executing node waits for the fs.readFileSync() function to get executed  After completion of the fs.readFileSync() method the remaining node program is executed.
  • 9. Syntax of fs.readFileSync()  Syntax: fs.readFileSync( path, options )  Parameters:  path: It takes the relative path of the text file. The path can be of URL type.  options: It is an optional parameter which contains the encoding and flag, the encoding contains data specification. It’s default value is null which returns raw buffer and the flag contains indication of operations in the file. It’s default value is ‘r’.  Example: const fs = require('fs'); const data = fs.readFileSync(‘app.js', {encoding:'utf8', flag:'r'});
  • 10. Example of fs.readFile() & fs.readFileSync() const fs = require('fs'); // Calling the fs.readFile() method for reading file fs.readFile(‘a.txt', {encoding:'utf8', flag:'r'}, function(err, data) { if(err) console.log(err); else console.log(data); }); // Calling the fs.readFileSync() method for reading file ‘b.txt' const data = fs.readFileSync(‘b.txt', {encoding:'utf8', flag:'r'});
  • 11. Writing to a File: fs.writeFile()  The fs.writeFile() method is used to asynchronously write the specified data to a file.  The file would be replaced if it ex  Syntax: fs.writeFile( file, data, options, callback )  Parameters: This method accept four parameters as mentioned above and described below:  file: It is a string denotes the path of the file where it has to be written.  data: It is a string, Buffer, TypedArray or DataView that will be written to the file.  options: It is an string or object that can be used to specify optional parameters that will affect the output. It has three optional parameter: encoding: It is a string value that specifies the encoding of the file. The default value is ‘utf8’. mode: It is an integer value that specifies the file mode. The default value is 0o666. flag: It is a string value that specifies the flag used while writing to the file. The default value is ‘w’.  callback: It is the function that would be called when the method is executed.
  • 12. Example of fs.writeFile() const fs = require('fs'); let data = "This is a file containing a a data n1111n 2222n 3333"; fs.writeFile(“a.txt", data, (err) => { if (err) console.log(err); else { console.log("File written successfullyn"); console.log("The written has the following contents:"); console.log(fs.readFileSync(“a.txt", "utf8")); } });
  • 13. Writing to a File: fs.writeFileSync()  The fs.writeFileSync() is a synchronous method.  The fs.writeFileSync() creates a new file if the specified file does not exist.  Syntax: fs.writeFileSync( file, data, options )  Parameters: This method accept three parameters as follows: file: It is a string, that denotes the path of the file where it has to be written. data: It is a string, Buffer, TypedArray or DataView that will be written to the file. options: It is an string or object that can be used to specify optional parameters that will affect the output. It has three optional parameter:  encoding: It is a string which specifies the encoding of the file. The default value is ‘utf8’.  mode: It is an integer which specifies the file mode. The default value is 0o666.  flag: It is a string which specifies the flag used while writing to the file.
  • 14. Example of fs.writeFileSync() const fs = require('fs'); let data = "This is a file containing a collection" + " of programming languages.n" + "1. Cn2. C++n3. Python"; fs.writeFileSync(“programming.txt", data); console.log("File written successfullyn"); console.log("The written has the following contents:"); console.log(fs.readFileSync("programming.txt", "utf8"));
  • 15. Appending to file fs.appendFile()  fs.appendFile() method is used to asynchronously append the given data to a file.  A new file is created if it does not exist.  Syntax fs.appendFile( path, data[, options], callback)  Parameters: This method accepts four parameters as mentioned above and described below: path: It is a String, Buffer, URL or number that denotes the source filename or file descriptor that will be appended to. data: It is a String or Buffer that denotes the data that has to be appended. options: It is an string or an object that can be used to specify optional parameters that will affect the output. It has three optional parameters:  encoding: It is a string which specifies the encoding of the file. The default value is ‘utf8’.  mode: It is an integer which specifies the file mode. The default value is ‘0o666’.  flag: It is a string which specifies the flag used while appending to the file. The default value is ‘a’. callback: It is a function that would be called when the method is executed.
  • 16. Appending to file fs.appendFile() const fs = require('fs'); // Get the file contents before the append operation console.log("nFile Contents of file before append:", var data=fs.readFileSync(“programming.txt”,{}) fs.readFileSync("example_file.txt", "utf8")); fs.appendFile("example_file.txt", data, (err) => { if (err) { console.log(err); } else { // Get the file contents after the append operation console.log("nFile Contents of file after append:“), console.log(fs.readFileSync("example_file.txt", "utf8")); } });
  • 17. Var fs=require(‘fs’)  Open  fs.open()  Write  fs.writeFileSync()  fs.writeFile()  Reading  fs.readFileSync()  fs.readFile()  Append  fs.appenFile() //asyn