File System
File System
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.
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)
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.
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()}`);
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!");
});
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 −
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