SlideShare a Scribd company logo
File System
1
Monica Deshmane(Haribhai V.Desai College,Pune)
Common use for the File System module:
1.Read files
2.Create files
3.Update files
4.Delete files
5.Rename files
2
Monica Deshmane(Haribhai V.Desai College,Pune)
FS Model
The Node File System (fs) module can be imported using
the following syntax −
var fs = require("fs")
Synchronous vs Asynchronous
Every method in the fs module has synchronous as well
as asynchronous forms.
Asynchronous methods take the last parameter as the
completion function callback and the first parameter of
the callback function as error.
3
Monica Deshmane(Haribhai V.Desai College,Pune)
Example
var fs = require("fs");
// Asynchronous read
fs.readFile('input.txt', function (err, data)
{ if (err) { return console.error(err); }
console.log("Asynchronous read: " + data.toString());
});
// Synchronous read
var data = fs.readFileSync('input.txt');
console.log("Synchronous read: " + data.toString());
console.log("Program Ended");
4
Monica Deshmane(Haribhai V.Desai College,Pune)
Important method of fs module
Method Description
fs.readFile(fileName [,options], callback) Reads existing file.
fs.writeFile(filename, data[, options], callback) Writes to the file. If file
exists then overwrite the
content otherwise creates
new file.
fs.open(path, flags[, mode], callback) Opens file for reading
or writing.
fs.rename(oldPath, newPath, callback) Renames an existing file.
fs.chown(path, uid, gid, callback) Asynchronous chown.
fs.stat(path, callback) Returns fs.stat object which
includes important file
statistics.
fs.link(src path, dst path, callback) Links file asynchronously.
fs.symlink(destination, path[, type], callback) Symlink asynchronously.
5
Monica Deshmane(Haribhai V.Desai College,Pune)
Important method of fs module
fs.utimes(path, atime, mtime, callback)
Changes the timestamp of the file.
fs.exists(path, callback)
Determines whether the specified file exists or not.
fs.access(path[, mode], callback)
Tests a user's permissions for the specified file.
fs.appendFile(file, data[, options], callback)
Appends new content to the existing file.
6
Monica Deshmane(Haribhai V.Desai College,Pune)
Opening Files
7
Monica Deshmane(Haribhai V.Desai College,Pune)
1) Open a File
Syntax : open a file in asynchronous mode −
fs.open (path, flags[, mode], callback)
Parameters-
1.path − This is the string having file name including path.
2.flags − Flags indicate the behavior of the file to be opened.
All possible values have been mentioned below.
3.mode − It sets the file mode (permission and sticky bits),
but only if the file was created. It defaults to 0666, readable
and writeable.
8
Monica Deshmane(Haribhai V.Desai College,Pune)
4.callback − This is the callback function which gets two arguments (err, fd).
Flags
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, asking 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 the 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 the path exists.
a+ : Open file for reading and appending. The file is created if it does not exist.
ax+ : Like 'a+' but fails if the the path exists.
9
Monica Deshmane(Haribhai V.Desai College,Pune)
Example
var fs = require("fs");
// Asynchronous - Opening File
console.log("Going to open file!");
fs.open('input.txt', 'r+', function(err, fd)
{ if (err)
{ return console.error(err); }
console.log("File opened successfully!"); });
Reading Files
10
Monica Deshmane(Haribhai V.Desai College,Pune)
2) Reading a File
Syntax −
fs.read(fd, buffer, offset, length, position, callback)
uses file descriptor to read the file.
fd − This is the file descriptor returned by fs.open().
buffer − This is the buffer that the data will be written to.
offset − This is the offset in the buffer to start writing at.
length − This is an integer specifying the number of bytes to read.
position − This is an integer specifying where to begin reading from
in the file. If position is null, data will be read from the current file
position.
callback − This is the callback function which gets the three
arguments, (err, bytesRead, buffer).
11
Monica Deshmane(Haribhai V.Desai College,Pune)
Example
var fs = require("fs");
var buf = new Buffer(1024);
console.log("Going to open an existing file");
fs.open('input.txt', 'r+', function(err, fd)
{ if (err) { return console.error(err); }
console.log("File opened successfully!");
console.log("Going to read the file");
fs.read (fd, buf, 0, buf.length, 0, function(err, bytes)
{ if (err){ console.log(err); }
console.log(bytes + " bytes read");
// Print only read bytes to avoid junk.
if(bytes > 0)
{ console.log(buf.slice(0,bytes).toString());
} });
})
12
Monica Deshmane(Haribhai V.Desai College,Pune)
Use fs.readFile() method to read the physical file asynchronously.
Syntax:
fs.readFile(fileName [,options], callback)
Parameter Description:
filename: Full path and name of the file as a string.
options: The options parameter can be an object or string
which can include encoding and flag. The default encoding is
utf8 and default flag is "r".
callback: A function with two parameters err and fd. This will
get called when readFile operation completes.
Reading Files : example
13
Monica Deshmane(Haribhai V.Desai College,Pune)
var fs = require('fs');
fs.readFile('TestFile.txt', function (err, data) {
if (err) throw err;
console.log(data);
});
run
14
Monica Deshmane(Haribhai V.Desai College,Pune)
The following is a sample TextFile.txt file.
TextFile.txt
This is test file to test fs module of Node.js
Now, run the above example and see the result as shown below.
C:> node server.js
This is test file to test fs module of Node.jsC:> node server.js
This is test file to test fs module of Node.js
Use fs.readFileSync() method to read file synchronously as shown below.
Example: Reading File Synchronously
var fs = require('fs');
var data = fs.readFileSync('dummyfile.txt', 'utf8');
console.log(data);
Writing a File
15
Monica Deshmane(Haribhai V.Desai College,Pune)
Syntax :
fs.writeFile(filename, data[, options], callback)
filename − This is the string having the file name including path.
data − This is the String or Buffer to be written into the file.
options − The third parameter is an object which will hold {encoding,
mode, flag}. By default. encoding is utf8, mode is octal value 0666. and
flag is 'w'
callback − This is the callback function which gets a single parameter
err that returns an error in case of any writing error.
Writing in File
16
Monica Deshmane(Haribhai V.Desai College,Pune)
var fs = require('fs');
fs.writeFile('mynewfile3.txt', 'This is my text',
function (err) {
if (err) throw err;
console.log('Replaced!');
});
Append file
17
Monica Deshmane(Haribhai V.Desai College,Pune)
var fs = require('fs');
fs.appendFile('mynewfile1.txt', 'HelloContent!',
function (err) {
if (err) throw err;
console.log('Saved!');
});
18
Monica Deshmane(Haribhai V.Desai College,Pune)
Other File Operations
Delete File
var fs = require('fs');
fs.unlink('mynewfile2.txt', function (err) {
if (err) throw err;
console.log('File deleted!');
});
Rename
var fs = require('fs');
fs.rename('mynewfile1.txt', 'myrenamedfile.txt', function (err) {
if (err) throw err;
console.log('File Renamed!');
});
19
Monica Deshmane(Haribhai V.Desai College,Pune)
Get File Information
Syntax : Following is the syntax of the method to get the
information about a file −
fs.stat(path, callback)
path − This is the string having file name including path.
callback − This is the callback function which gets two arguments
(err, stats) where stats is an object of fs.Stats type which is printed
below in the example.
20
Monica Deshmane(Haribhai V.Desai College,Pune)
Get File Information
Method & Description
stats.isFile() : Returns true if file type of a simple file.
stats.isDirectory() : Returns true if file type of a directory.
stats.isBlockDevice() : Returns true if file type of a block
device.
stats.isCharacterDevice() : Returns true if file type of a character
device.
stats.isSymbolicLink() : Returns true if file type of a symbolic link.
stats.isFIFO() : Returns true if file type of a FIFO.
stats.isSocket() : Returns true if file type of a socket.
21
Monica Deshmane(Haribhai V.Desai College,Pune)
Get File Information
Example
var fs = require("fs");
console.log("Going to get file info!");
fs.stat('input.txt', function (err, stats)
{ if (err)
{ return console.error(err); }
console.log(stats);
console.log("Got file info successfully!");
// Check file type
console.log("isFile ? " + stats.isFile());
console.log("isDirectory ? " + stats.isDirectory()); });
Monica Deshmane(Haribhai V.Desai College,Pune) 22
Question Bank—
Assignment-
1.Explain syntax, run example & display output of each operation
on file
1) Readfile()
2) readFileSync()
3) Read()
4) Open()
5) Truncate()
6) ftruncate()
7) append file
8) Rename()
9) Write file
10) Writefilesync()
11) Write()
12) Chmod
13) Stat()
14) Fstat()
15) Link
16) symlink
17)Readlink
18)Unlink()
19)chown()
20)lchown()
21)fchown()
Any Questions?
23
Monica Deshmane(Haribhai V.Desai College,Pune)

More Related Content

What's hot

Html 5
Html 5Html 5
Class 5 - PHP Strings
Class 5 - PHP StringsClass 5 - PHP Strings
Class 5 - PHP Strings
Ahmed Swilam
 
Data file handling in c++
Data file handling in c++Data file handling in c++
Data file handling in c++
Vineeta Garg
 
Javascript 101
Javascript 101Javascript 101
Javascript 101
Shlomi Komemi
 
JavaScript - Chapter 12 - Document Object Model
  JavaScript - Chapter 12 - Document Object Model  JavaScript - Chapter 12 - Document Object Model
JavaScript - Chapter 12 - Document Object Model
WebStackAcademy
 
Javascript
JavascriptJavascript
Javascript
guest03a6e6
 
Node.js Express
Node.js  ExpressNode.js  Express
Node.js Express
Eyal Vardi
 
Php
PhpPhp
PHP
PHPPHP
Lab #2: Introduction to Javascript
Lab #2: Introduction to JavascriptLab #2: Introduction to Javascript
Lab #2: Introduction to Javascript
Walid Ashraf
 
JSON: The Basics
JSON: The BasicsJSON: The Basics
JSON: The Basics
Jeff Fox
 
Files in java
Files in javaFiles in java
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
Seble Nigussie
 
A Basic Django Introduction
A Basic Django IntroductionA Basic Django Introduction
A Basic Django Introduction
Ganga Ram
 
File handling in Python
File handling in PythonFile handling in Python
Angular - Chapter 4 - Data and Event Handling
 Angular - Chapter 4 - Data and Event Handling Angular - Chapter 4 - Data and Event Handling
Angular - Chapter 4 - Data and Event Handling
WebStackAcademy
 
File Management in C
File Management in CFile Management in C
File Management in C
Paurav Shah
 
Python programming : Files
Python programming : FilesPython programming : Files
Python programming : Files
Emertxe Information Technologies Pvt Ltd
 
jQuery
jQueryjQuery
Php basics
Php basicsPhp basics
Php basics
Jamshid Hashimi
 

What's hot (20)

Html 5
Html 5Html 5
Html 5
 
Class 5 - PHP Strings
Class 5 - PHP StringsClass 5 - PHP Strings
Class 5 - PHP Strings
 
Data file handling in c++
Data file handling in c++Data file handling in c++
Data file handling in c++
 
Javascript 101
Javascript 101Javascript 101
Javascript 101
 
JavaScript - Chapter 12 - Document Object Model
  JavaScript - Chapter 12 - Document Object Model  JavaScript - Chapter 12 - Document Object Model
JavaScript - Chapter 12 - Document Object Model
 
Javascript
JavascriptJavascript
Javascript
 
Node.js Express
Node.js  ExpressNode.js  Express
Node.js Express
 
Php
PhpPhp
Php
 
PHP
PHPPHP
PHP
 
Lab #2: Introduction to Javascript
Lab #2: Introduction to JavascriptLab #2: Introduction to Javascript
Lab #2: Introduction to Javascript
 
JSON: The Basics
JSON: The BasicsJSON: The Basics
JSON: The Basics
 
Files in java
Files in javaFiles in java
Files in java
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
 
A Basic Django Introduction
A Basic Django IntroductionA Basic Django Introduction
A Basic Django Introduction
 
File handling in Python
File handling in PythonFile handling in Python
File handling in Python
 
Angular - Chapter 4 - Data and Event Handling
 Angular - Chapter 4 - Data and Event Handling Angular - Chapter 4 - Data and Event Handling
Angular - Chapter 4 - Data and Event Handling
 
File Management in C
File Management in CFile Management in C
File Management in C
 
Python programming : Files
Python programming : FilesPython programming : Files
Python programming : Files
 
jQuery
jQueryjQuery
jQuery
 
Php basics
Php basicsPhp basics
Php basics
 

Similar to File system node js

FS_module_functions.pptx
FS_module_functions.pptxFS_module_functions.pptx
FS_module_functions.pptx
Bareen Shaikh
 
Chap 5 php files part 1
Chap 5 php files part 1Chap 5 php files part 1
Chap 5 php files part 1
monikadeshmane
 
Php files
Php filesPhp files
Php files
kalyani66
 
Files nts
Files ntsFiles nts
Files nts
kalyani66
 
FILES IN C
FILES IN CFILES IN C
FILES IN C
yndaravind
 
Tutorial on Node File System
Tutorial on Node File SystemTutorial on Node File System
Tutorial on Node File System
iFour Technolab Pvt. Ltd.
 
file handling1
file handling1file handling1
file handling1
student
 
File handling
File handlingFile handling
File handling
Swarup Kumar Boro
 
C Programming Unit-5
C Programming Unit-5C Programming Unit-5
C Programming Unit-5
Vikram Nandini
 
Unit-VI.pptx
Unit-VI.pptxUnit-VI.pptx
Unit-VI.pptx
Mehul Desai
 
18CS56-UP-Module 3.pptx
18CS56-UP-Module 3.pptx18CS56-UP-Module 3.pptx
18CS56-UP-Module 3.pptx
ChenamPawan
 
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reugeFile handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
vsol7206
 
Unit5
Unit5Unit5
Unit5
mrecedu
 
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
AssadLeo1
 
Unit 5 dwqb ans
Unit 5 dwqb ansUnit 5 dwqb ans
Unit 5 dwqb ans
Sowri Rajan
 
Filesin c++
Filesin c++Filesin c++
Filesin c++
HalaiHansaika
 
File System in Nodejs.pdf
File System in Nodejs.pdfFile System in Nodejs.pdf
File System in Nodejs.pdf
SudhanshiBakre1
 
Functions in python
Functions in pythonFunctions in python
Functions in python
Santosh Verma
 
4 text file
4 text file4 text file
4 text file
hasan Mohammad
 
Hands On Intro to Node.js
Hands On Intro to Node.jsHands On Intro to Node.js
Hands On Intro to Node.js
Chris Cowan
 

Similar to File system node js (20)

FS_module_functions.pptx
FS_module_functions.pptxFS_module_functions.pptx
FS_module_functions.pptx
 
Chap 5 php files part 1
Chap 5 php files part 1Chap 5 php files part 1
Chap 5 php files part 1
 
Php files
Php filesPhp files
Php files
 
Files nts
Files ntsFiles nts
Files nts
 
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
 
file handling1
file handling1file handling1
file handling1
 
File handling
File handlingFile handling
File handling
 
C Programming Unit-5
C Programming Unit-5C Programming Unit-5
C Programming Unit-5
 
Unit-VI.pptx
Unit-VI.pptxUnit-VI.pptx
Unit-VI.pptx
 
18CS56-UP-Module 3.pptx
18CS56-UP-Module 3.pptx18CS56-UP-Module 3.pptx
18CS56-UP-Module 3.pptx
 
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reugeFile handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
 
Unit5
Unit5Unit5
Unit5
 
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
 
Unit 5 dwqb ans
Unit 5 dwqb ansUnit 5 dwqb ans
Unit 5 dwqb ans
 
Filesin c++
Filesin c++Filesin c++
Filesin c++
 
File System in Nodejs.pdf
File System in Nodejs.pdfFile System in Nodejs.pdf
File System in Nodejs.pdf
 
Functions in python
Functions in pythonFunctions in python
Functions in python
 
4 text file
4 text file4 text file
4 text file
 
Hands On Intro to Node.js
Hands On Intro to Node.jsHands On Intro to Node.js
Hands On Intro to Node.js
 

More from monikadeshmane

Intsllation & 1st program nodejs
Intsllation & 1st program nodejsIntsllation & 1st program nodejs
Intsllation & 1st program nodejs
monikadeshmane
 
Nodejs basics
Nodejs basicsNodejs basics
Nodejs basics
monikadeshmane
 
Chap 5 php files part-2
Chap 5 php files   part-2Chap 5 php files   part-2
Chap 5 php files part-2
monikadeshmane
 
Chap4 oop class (php) part 2
Chap4 oop class (php) part 2Chap4 oop class (php) part 2
Chap4 oop class (php) part 2
monikadeshmane
 
Chap4 oop class (php) part 1
Chap4 oop class (php) part 1Chap4 oop class (php) part 1
Chap4 oop class (php) part 1
monikadeshmane
 
Chap 3php array part4
Chap 3php array part4Chap 3php array part4
Chap 3php array part4
monikadeshmane
 
Chap 3php array part 3
Chap 3php array part 3Chap 3php array part 3
Chap 3php array part 3
monikadeshmane
 
Chap 3php array part 2
Chap 3php array part 2Chap 3php array part 2
Chap 3php array part 2
monikadeshmane
 
Chap 3php array part1
Chap 3php array part1Chap 3php array part1
Chap 3php array part1
monikadeshmane
 
PHP function
PHP functionPHP function
PHP function
monikadeshmane
 
php string part 4
php string part 4php string part 4
php string part 4
monikadeshmane
 
php string part 3
php string part 3php string part 3
php string part 3
monikadeshmane
 
php string-part 2
php string-part 2php string-part 2
php string-part 2
monikadeshmane
 
PHP string-part 1
PHP string-part 1PHP string-part 1
PHP string-part 1
monikadeshmane
 
java script
java scriptjava script
java script
monikadeshmane
 
ip1clientserver model
 ip1clientserver model ip1clientserver model
ip1clientserver model
monikadeshmane
 
Chap1introppt2php(finally done)
Chap1introppt2php(finally done)Chap1introppt2php(finally done)
Chap1introppt2php(finally done)
monikadeshmane
 
Chap1introppt1php basic
Chap1introppt1php basicChap1introppt1php basic
Chap1introppt1php basic
monikadeshmane
 

More from monikadeshmane (18)

Intsllation & 1st program nodejs
Intsllation & 1st program nodejsIntsllation & 1st program nodejs
Intsllation & 1st program nodejs
 
Nodejs basics
Nodejs basicsNodejs basics
Nodejs basics
 
Chap 5 php files part-2
Chap 5 php files   part-2Chap 5 php files   part-2
Chap 5 php files part-2
 
Chap4 oop class (php) part 2
Chap4 oop class (php) part 2Chap4 oop class (php) part 2
Chap4 oop class (php) part 2
 
Chap4 oop class (php) part 1
Chap4 oop class (php) part 1Chap4 oop class (php) part 1
Chap4 oop class (php) part 1
 
Chap 3php array part4
Chap 3php array part4Chap 3php array part4
Chap 3php array part4
 
Chap 3php array part 3
Chap 3php array part 3Chap 3php array part 3
Chap 3php array part 3
 
Chap 3php array part 2
Chap 3php array part 2Chap 3php array part 2
Chap 3php array part 2
 
Chap 3php array part1
Chap 3php array part1Chap 3php array part1
Chap 3php array part1
 
PHP function
PHP functionPHP function
PHP function
 
php string part 4
php string part 4php string part 4
php string part 4
 
php string part 3
php string part 3php string part 3
php string part 3
 
php string-part 2
php string-part 2php string-part 2
php string-part 2
 
PHP string-part 1
PHP string-part 1PHP string-part 1
PHP string-part 1
 
java script
java scriptjava script
java script
 
ip1clientserver model
 ip1clientserver model ip1clientserver model
ip1clientserver model
 
Chap1introppt2php(finally done)
Chap1introppt2php(finally done)Chap1introppt2php(finally done)
Chap1introppt2php(finally done)
 
Chap1introppt1php basic
Chap1introppt1php basicChap1introppt1php basic
Chap1introppt1php basic
 

Recently uploaded

ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdfANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
Priyankaranawat4
 
Hindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdfHindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdf
Dr. Mulla Adam Ali
 
The Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collectionThe Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collection
Israel Genealogy Research Association
 
PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.
Dr. Shivangi Singh Parihar
 
The basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptxThe basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptx
heathfieldcps1
 
Présentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptx
Présentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptxPrésentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptx
Présentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptx
siemaillard
 
A Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdfA Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdf
Jean Carlos Nunes Paixão
 
UGC NET Exam Paper 1- Unit 1:Teaching Aptitude
UGC NET Exam Paper 1- Unit 1:Teaching AptitudeUGC NET Exam Paper 1- Unit 1:Teaching Aptitude
UGC NET Exam Paper 1- Unit 1:Teaching Aptitude
S. Raj Kumar
 
Pengantar Penggunaan Flutter - Dart programming language1.pptx
Pengantar Penggunaan Flutter - Dart programming language1.pptxPengantar Penggunaan Flutter - Dart programming language1.pptx
Pengantar Penggunaan Flutter - Dart programming language1.pptx
Fajar Baskoro
 
BBR 2024 Summer Sessions Interview Training
BBR  2024 Summer Sessions Interview TrainingBBR  2024 Summer Sessions Interview Training
BBR 2024 Summer Sessions Interview Training
Katrina Pritchard
 
Main Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docxMain Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docx
adhitya5119
 
writing about opinions about Australia the movie
writing about opinions about Australia the moviewriting about opinions about Australia the movie
writing about opinions about Australia the movie
Nicholas Montgomery
 
Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...
Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...
Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...
imrankhan141184
 
How to Setup Warehouse & Location in Odoo 17 Inventory
How to Setup Warehouse & Location in Odoo 17 InventoryHow to Setup Warehouse & Location in Odoo 17 Inventory
How to Setup Warehouse & Location in Odoo 17 Inventory
Celine George
 
Reimagining Your Library Space: How to Increase the Vibes in Your Library No ...
Reimagining Your Library Space: How to Increase the Vibes in Your Library No ...Reimagining Your Library Space: How to Increase the Vibes in Your Library No ...
Reimagining Your Library Space: How to Increase the Vibes in Your Library No ...
Diana Rendina
 
How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17
Celine George
 
Digital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental DesignDigital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental Design
amberjdewit93
 
Beyond Degrees - Empowering the Workforce in the Context of Skills-First.pptx
Beyond Degrees - Empowering the Workforce in the Context of Skills-First.pptxBeyond Degrees - Empowering the Workforce in the Context of Skills-First.pptx
Beyond Degrees - Empowering the Workforce in the Context of Skills-First.pptx
EduSkills OECD
 
Liberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdfLiberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdf
WaniBasim
 
MARY JANE WILSON, A “BOA MÃE” .
MARY JANE WILSON, A “BOA MÃE”           .MARY JANE WILSON, A “BOA MÃE”           .
MARY JANE WILSON, A “BOA MÃE” .
Colégio Santa Teresinha
 

Recently uploaded (20)

ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdfANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
 
Hindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdfHindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdf
 
The Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collectionThe Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collection
 
PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.
 
The basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptxThe basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptx
 
Présentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptx
Présentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptxPrésentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptx
Présentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptx
 
A Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdfA Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdf
 
UGC NET Exam Paper 1- Unit 1:Teaching Aptitude
UGC NET Exam Paper 1- Unit 1:Teaching AptitudeUGC NET Exam Paper 1- Unit 1:Teaching Aptitude
UGC NET Exam Paper 1- Unit 1:Teaching Aptitude
 
Pengantar Penggunaan Flutter - Dart programming language1.pptx
Pengantar Penggunaan Flutter - Dart programming language1.pptxPengantar Penggunaan Flutter - Dart programming language1.pptx
Pengantar Penggunaan Flutter - Dart programming language1.pptx
 
BBR 2024 Summer Sessions Interview Training
BBR  2024 Summer Sessions Interview TrainingBBR  2024 Summer Sessions Interview Training
BBR 2024 Summer Sessions Interview Training
 
Main Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docxMain Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docx
 
writing about opinions about Australia the movie
writing about opinions about Australia the moviewriting about opinions about Australia the movie
writing about opinions about Australia the movie
 
Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...
Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...
Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...
 
How to Setup Warehouse & Location in Odoo 17 Inventory
How to Setup Warehouse & Location in Odoo 17 InventoryHow to Setup Warehouse & Location in Odoo 17 Inventory
How to Setup Warehouse & Location in Odoo 17 Inventory
 
Reimagining Your Library Space: How to Increase the Vibes in Your Library No ...
Reimagining Your Library Space: How to Increase the Vibes in Your Library No ...Reimagining Your Library Space: How to Increase the Vibes in Your Library No ...
Reimagining Your Library Space: How to Increase the Vibes in Your Library No ...
 
How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17
 
Digital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental DesignDigital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental Design
 
Beyond Degrees - Empowering the Workforce in the Context of Skills-First.pptx
Beyond Degrees - Empowering the Workforce in the Context of Skills-First.pptxBeyond Degrees - Empowering the Workforce in the Context of Skills-First.pptx
Beyond Degrees - Empowering the Workforce in the Context of Skills-First.pptx
 
Liberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdfLiberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdf
 
MARY JANE WILSON, A “BOA MÃE” .
MARY JANE WILSON, A “BOA MÃE”           .MARY JANE WILSON, A “BOA MÃE”           .
MARY JANE WILSON, A “BOA MÃE” .
 

File system node js

  • 2. Common use for the File System module: 1.Read files 2.Create files 3.Update files 4.Delete files 5.Rename files 2 Monica Deshmane(Haribhai V.Desai College,Pune)
  • 3. FS Model The Node File System (fs) module can be imported using the following syntax − var fs = require("fs") Synchronous vs Asynchronous Every method in the fs module has synchronous as well as asynchronous forms. Asynchronous methods take the last parameter as the completion function callback and the first parameter of the callback function as error. 3 Monica Deshmane(Haribhai V.Desai College,Pune)
  • 4. Example var fs = require("fs"); // Asynchronous read fs.readFile('input.txt', function (err, data) { if (err) { return console.error(err); } console.log("Asynchronous read: " + data.toString()); }); // Synchronous read var data = fs.readFileSync('input.txt'); console.log("Synchronous read: " + data.toString()); console.log("Program Ended"); 4 Monica Deshmane(Haribhai V.Desai College,Pune)
  • 5. Important method of fs module Method Description fs.readFile(fileName [,options], callback) Reads existing file. fs.writeFile(filename, data[, options], callback) Writes to the file. If file exists then overwrite the content otherwise creates new file. fs.open(path, flags[, mode], callback) Opens file for reading or writing. fs.rename(oldPath, newPath, callback) Renames an existing file. fs.chown(path, uid, gid, callback) Asynchronous chown. fs.stat(path, callback) Returns fs.stat object which includes important file statistics. fs.link(src path, dst path, callback) Links file asynchronously. fs.symlink(destination, path[, type], callback) Symlink asynchronously. 5 Monica Deshmane(Haribhai V.Desai College,Pune)
  • 6. Important method of fs module fs.utimes(path, atime, mtime, callback) Changes the timestamp of the file. fs.exists(path, callback) Determines whether the specified file exists or not. fs.access(path[, mode], callback) Tests a user's permissions for the specified file. fs.appendFile(file, data[, options], callback) Appends new content to the existing file. 6 Monica Deshmane(Haribhai V.Desai College,Pune)
  • 7. Opening Files 7 Monica Deshmane(Haribhai V.Desai College,Pune) 1) Open a File Syntax : open a file in asynchronous mode − fs.open (path, flags[, mode], callback) Parameters- 1.path − This is the string having file name including path. 2.flags − Flags indicate the behavior of the file to be opened. All possible values have been mentioned below. 3.mode − It sets the file mode (permission and sticky bits), but only if the file was created. It defaults to 0666, readable and writeable.
  • 8. 8 Monica Deshmane(Haribhai V.Desai College,Pune) 4.callback − This is the callback function which gets two arguments (err, fd). Flags 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, asking 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 the 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 the path exists. a+ : Open file for reading and appending. The file is created if it does not exist. ax+ : Like 'a+' but fails if the the path exists.
  • 9. 9 Monica Deshmane(Haribhai V.Desai College,Pune) Example var fs = require("fs"); // Asynchronous - Opening File console.log("Going to open file!"); fs.open('input.txt', 'r+', function(err, fd) { if (err) { return console.error(err); } console.log("File opened successfully!"); });
  • 10. Reading Files 10 Monica Deshmane(Haribhai V.Desai College,Pune) 2) Reading a File Syntax − fs.read(fd, buffer, offset, length, position, callback) uses file descriptor to read the file. fd − This is the file descriptor returned by fs.open(). buffer − This is the buffer that the data will be written to. offset − This is the offset in the buffer to start writing at. length − This is an integer specifying the number of bytes to read. position − This is an integer specifying where to begin reading from in the file. If position is null, data will be read from the current file position. callback − This is the callback function which gets the three arguments, (err, bytesRead, buffer).
  • 11. 11 Monica Deshmane(Haribhai V.Desai College,Pune) Example var fs = require("fs"); var buf = new Buffer(1024); console.log("Going to open an existing file"); fs.open('input.txt', 'r+', function(err, fd) { if (err) { return console.error(err); } console.log("File opened successfully!"); console.log("Going to read the file"); fs.read (fd, buf, 0, buf.length, 0, function(err, bytes) { if (err){ console.log(err); } console.log(bytes + " bytes read"); // Print only read bytes to avoid junk. if(bytes > 0) { console.log(buf.slice(0,bytes).toString()); } }); })
  • 12. 12 Monica Deshmane(Haribhai V.Desai College,Pune) Use fs.readFile() method to read the physical file asynchronously. Syntax: fs.readFile(fileName [,options], callback) Parameter Description: filename: Full path and name of the file as a string. options: The options parameter can be an object or string which can include encoding and flag. The default encoding is utf8 and default flag is "r". callback: A function with two parameters err and fd. This will get called when readFile operation completes.
  • 13. Reading Files : example 13 Monica Deshmane(Haribhai V.Desai College,Pune) var fs = require('fs'); fs.readFile('TestFile.txt', function (err, data) { if (err) throw err; console.log(data); });
  • 14. run 14 Monica Deshmane(Haribhai V.Desai College,Pune) The following is a sample TextFile.txt file. TextFile.txt This is test file to test fs module of Node.js Now, run the above example and see the result as shown below. C:> node server.js This is test file to test fs module of Node.jsC:> node server.js This is test file to test fs module of Node.js Use fs.readFileSync() method to read file synchronously as shown below. Example: Reading File Synchronously var fs = require('fs'); var data = fs.readFileSync('dummyfile.txt', 'utf8'); console.log(data);
  • 15. Writing a File 15 Monica Deshmane(Haribhai V.Desai College,Pune) Syntax : fs.writeFile(filename, data[, options], callback) filename − This is the string having the file name including path. data − This is the String or Buffer to be written into the file. options − The third parameter is an object which will hold {encoding, mode, flag}. By default. encoding is utf8, mode is octal value 0666. and flag is 'w' callback − This is the callback function which gets a single parameter err that returns an error in case of any writing error.
  • 16. Writing in File 16 Monica Deshmane(Haribhai V.Desai College,Pune) var fs = require('fs'); fs.writeFile('mynewfile3.txt', 'This is my text', function (err) { if (err) throw err; console.log('Replaced!'); });
  • 17. Append file 17 Monica Deshmane(Haribhai V.Desai College,Pune) var fs = require('fs'); fs.appendFile('mynewfile1.txt', 'HelloContent!', function (err) { if (err) throw err; console.log('Saved!'); });
  • 18. 18 Monica Deshmane(Haribhai V.Desai College,Pune) Other File Operations Delete File var fs = require('fs'); fs.unlink('mynewfile2.txt', function (err) { if (err) throw err; console.log('File deleted!'); }); Rename var fs = require('fs'); fs.rename('mynewfile1.txt', 'myrenamedfile.txt', function (err) { if (err) throw err; console.log('File Renamed!'); });
  • 19. 19 Monica Deshmane(Haribhai V.Desai College,Pune) Get File Information Syntax : Following is the syntax of the method to get the information about a file − fs.stat(path, callback) path − This is the string having file name including path. callback − This is the callback function which gets two arguments (err, stats) where stats is an object of fs.Stats type which is printed below in the example.
  • 20. 20 Monica Deshmane(Haribhai V.Desai College,Pune) Get File Information Method & Description stats.isFile() : Returns true if file type of a simple file. stats.isDirectory() : Returns true if file type of a directory. stats.isBlockDevice() : Returns true if file type of a block device. stats.isCharacterDevice() : Returns true if file type of a character device. stats.isSymbolicLink() : Returns true if file type of a symbolic link. stats.isFIFO() : Returns true if file type of a FIFO. stats.isSocket() : Returns true if file type of a socket.
  • 21. 21 Monica Deshmane(Haribhai V.Desai College,Pune) Get File Information Example var fs = require("fs"); console.log("Going to get file info!"); fs.stat('input.txt', function (err, stats) { if (err) { return console.error(err); } console.log(stats); console.log("Got file info successfully!"); // Check file type console.log("isFile ? " + stats.isFile()); console.log("isDirectory ? " + stats.isDirectory()); });
  • 22. Monica Deshmane(Haribhai V.Desai College,Pune) 22 Question Bank— Assignment- 1.Explain syntax, run example & display output of each operation on file 1) Readfile() 2) readFileSync() 3) Read() 4) Open() 5) Truncate() 6) ftruncate() 7) append file 8) Rename() 9) Write file 10) Writefilesync() 11) Write() 12) Chmod 13) Stat() 14) Fstat() 15) Link 16) symlink 17)Readlink 18)Unlink() 19)chown() 20)lchown() 21)fchown()