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

File System

The document provides an overview of the Node.js fs module, detailing its asynchronous and synchronous file I/O operations. It lists various methods available for file manipulation, such as fs.readFile, fs.writeFile, and fs.mkdir, along with examples of their usage. Additionally, it explains how to check file permissions and existence, manage directories, and retrieve file information using fs.stat.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

File System

The document provides an overview of the Node.js fs module, detailing its asynchronous and synchronous file I/O operations. It lists various methods available for file manipulation, such as fs.readFile, fs.writeFile, and fs.mkdir, along with examples of their usage. Additionally, it explains how to check file permissions and existence, manage directories, and retrieve file information using fs.stat.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 25

File System

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.

fs = require('fs')

One peculiar thing about the fs module is that all the methods are asynchronous by
default, but they can also work synchronously by appending Sync.

For example:
fs.rename()
fs.renameSync()
fs.write()
fs.writeSync()
This makes a huge difference in your application flow.

Following methods are made available for use.

•Blocking methods execute Synchronously


•Non-blocking methods execute Asynchronously
fs.access(): check if the file exists and Node.js can access it with its permissions
•fs.appendFile(): append data to a file. If the file does not exist, it's created
•fs.chmod(): change the permissions of a file specified by the filename passed. Related: fs.lchmod(
•fs.chown(): change the owner and group of a file specified by the filename passed. Related: fs.fch
•fs.close(): close a file descriptor
•fs.copyFile(): copies a file
•fs.createReadStream(): create a readable file stream
•fs.createWriteStream(): create a writable file stream
•fs.link(): create a new hard link to a file
•fs.mkdir(): create a new folder
•fs.mkdtemp(): create a temporary directory
•fs.open(): set the file mode
•fs.readdir(): read the contents of a directory
•fs.readFile(): read the content of a file. Related: fs.read()
•fs.readlink(): read the value of a symbolic link
•fs.realpath(): resolve relative file path pointers (., ..) to the full path
•fs.rename(): rename a file or folder
•fs.rmdir(): remove a folder
•fs.stat(): returns the status of the file identified by the filename passed. Related: fs.fstat(), fs.lstat()
•fs.symlink(): create a new symbolic link to a file
•fs.truncate(): truncate to the specified length the file identified by the filename passed. Related: fs
•fs.unlink(): remove a file or a symbolic link
•fs.unwatchFile(): stop watching for changes on a file
•fs.utimes(): change the timestamp of the file identified by the filename passed. Related: fs.futimes
•fs.watchFile(): start watching for changes on a file. Related: fs.watch()

Working with Files
var fs=require('fs');
fs.readFile('example1.txt',function(err,data)
{
if(!err)
console.log("SUCCESS");
console.log(data.toString());
});
var fs=require('fs');
fs.writeFile('example1.txt','WELCOME',function(err)
{
if(err)
console.log("ERROR in FILE");
else
console.log("SUCCESS!!!!!!!!!!!");
});

var fs=require('fs');
fs.appendFile('example1.txt','Have a Nice DAY!!!!!!',function(err)
{
if(err)
console.log("ERROR in FILE");
else
console.log("SUCCESS!!!!!!!!!!!");
});
var fs=require('fs');
fs.rename('example1.txt','ex.txt',function(err)
{if(err)
console.log("ERROR in Renaming");
});

var fs=require('fs');
fs.unlink('ex.txt',function(err)
{if(err)
console.log("ERROR")});
var fs=require('fs')
fs.rename('test.txt','test2.txt',function(err) {

console.log("\nFile Renamed!\n");
console.log('Success'); Old file ---- test.txt
Renamed ----- test2.txt
});

var fs=require('fs')
fs.rename('test.txt','test2.txt',() => {
console.log("\nFile Renamed!\n");
console.log('Success');

});
readFile and readFileSync
k ing
c
Blo var fs=require('fs');
function morework()
{console.log("I am more work function");}
var data=fs.readFileSync('test2.txt');
console.log(data.toString());
C:\msc\Node\filesystem>node readfile_syn.js
morework();
WELCOME
I am more work function

g
o ckin
l
n -B
Novar fs=require('fs');
function morework()
{console.log("I am more work function");}
fs.readFile('test2.txt',(err,data)=>{
console.log(data.toString());
});
morework(); C:\msc\Node\filesystem>node readfile_asy.js
I am more work function
WELCOME
Syntax
fs.readFile(fileName [,options], callback)

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.

var fs = require('fs');
fs.readFile('TestFile.txt', function (err, data)
{ if (err) throw err;
console.log(data);
});

The above example reads TestFile.txt (on Windows) asynchronously and executes
callback function when read operation completes. This read operation either throws an
error or completes successfully. The err parameter contains error information if any.
The data parameter contains the content of the specified file.

Reading File Synchronously


Myfile.txt
We are Learning Node JS File System.

Main.js
var fs=require('fs');
fs.readFile(('myfile.txt'),function(myerror,data)
{
if(myerror)
{ return console.error(myerror); }
console.log("Reading Asynchronous : "+data.toString());
});
var data=fs.readFileSync('myfile.txt');
console.log("Reading synchronous : "+data.toString());
console.log("The End");
var fs=require('fs');
function morework()
{console.log("I am more work function");}
fs.writeFileSync('test2.txt',`${morework.toString()}`);

Execute -- C:\msc\Node\filesystem>node writefile_syn.js

Open test2.txt

function morework()
{console.log("I am more work function");}
fs.access( path, mode, callback )

The fs.access() method is used to test the permissions of a given file or directory. The
permissions to be checked can be specified as a parameter using file access constants. It
is also possible to check multiple file permissions by using the bitwise OR operator to
create a mask with more than one file constant.

Note: It is not recommended to use the fs.access() method to check for the accessiblity
of a file before calling fs.open(), fs.readFile() or fs.writeFile(), because it introduces a
race condition since the file state may be changed by other processes after the test.

const fs = require('fs');
fs.access('myfile.txt', fs.constants.F_OK, (err) => {
console.log('\n> Checking if the file exists');
if (err) {
console.error('File does not exist'); }
else
{console.error('File exist'); }
});
Checking Read, Write and Existence
Working with Directories
1. Creating Directories

var fs = require("fs");
console.log("Going to create directory /msc/test");
//creating sub directories ie msc-folder subfolder-test
fs.mkdir('/msc/test',function(err) {
if (err) {
return console.error(err);
}
console.log("Directory created successfully!");
});

console.log("Going to create directory -- test");


//creating directory-test
fs.mkdir(“test”,function(err) {
var fs = require("fs");
console.log("Going to create directory /msc/test");
fs.mkdirSync('/msc/testing');
console.log("Directory created successfully!");

var fs = require("fs");
console.log("Going to Rename directory /msc/test");
fs.rename('/msc/testing’,'/msc/check',function(err) {
console.log("Renamed successfully!");
});

var fs = require("fs");
fs.rmdirSync('/msc/testing');
console.log("Directory removed successfully!");
2. Checking the Existence of the Directory

var fs = require("fs");
fs.access(“test",function(err)
{
if (err)
{
console.log("Directory does not Exists!");
}
else
{
console.log("Directory Existed!");
}
});
fs.exists() is deprecated, but fs.existsSync() is not.
fs.existsSync() does not use a callback.

var fs = require("fs");
let fileExists = fs.existsSync('hello.txt');
console.log("hello.txt exists:", fileExists);

Output
Boolean value
Flags
Flags for read/write operations are −

Sr.No. Flag & Description


1 r
Open file for reading. An exception occurs if the file does not exist.
2 r+
Open file for reading and writing. An exception occurs if the file does not exist.
3 rs
Open file for reading in synchronous mode.
4 rs+
Open file for reading and writing, asking the OS to open it synchronously. See notes for 'rs' about using this with
caution.
5 w
Open file for writing. The file is created (if it does not exist) or truncated (if it exists).
6 wx
Like 'w' but fails if the path exists.
7 w+
Open file for reading and writing. The file is created (if it does not exist) or truncated (if it exists).
8 wx+
Like 'w+' but fails if path exists.
9 a
Open file for appending. The file is created if it does not exist.
10 ax
Like 'a' but fails if the path exists.
11 a+
Open file for reading and appending. The file is created if it does not exist.
12 ax+
Like 'a+' but fails if the the path exists.
Example
Let us create a js file named main.js having the following code to
open a file input.txt for reading and writing.

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); }
else
{
console.log("File opened successfully!");
//read
//write
fs.close(fd,(err)=>{console.log(“File Closed”);})
}
Get File Information
Syntax
Following is the syntax of the method to get the information about a file −
fs.stat(path, callback)

Parameters
Here is the description of the parameters used −
•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.

Apart from the important attributes which are printed below in the example, there are
several useful methods available in fs.Stats class which can be used to check file type.
These methods are given in the following table.
Sr.N Method & Description
o.
1 stats.isFile()
Returns true if file type of a simple file.
2 stats.isDirectory()
Returns true if file type of a directory.
3 stats.isBlockDevice()
Returns true if file type of a block device.
4 stats.isCharacterDevice()
Returns true if file type of a character device.
5 stats.isSymbolicLink()
Returns true if file type of a symbolic link.
6 stats.isFIFO()
Returns true if file type of a FIFO.
7 stats.isSocket()
Returns true if file type of a socket.
Let us create a js file named main.js with the following code −

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());
console.log(stats.size);
});
https://nodejs.org/api/fs.html

You might also like