Home >>Nodejs Tutorial >Node.js - File System

Node.js - File System

Node.js - File System

Using simple wrappers around standard POSIX functions Node implements File I / O. You may import the Node File System (fs) module using the following syntax.

var fs = require("fs")

Synchronous vs Asynchronous

In the fs module each method has both synchronous and asynchronous forms. Asynchronous methods take the final parameter as the callback completion function and the first callback function parameter as error. Rather than using a synchronous method, it is better to use an asynchronous method, since the former never blocks a program during its execution, while the latter does.

Example

Creates a text file named input.txt with the content –

Keep Training and keep Learning

Until you get it Right !!!!!

Let's create a Js file named main.js with the code –

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");

Run main.js now to see the result –

$ node main.js
Verify the Output
Synchronous read: Keep Training and keep Learning
Until you get it Right !!!!!
Program Ended
Asynchronous read: Keep Training and keep Learning
Until you get it Right !!!!!

The following sections in this chapter include a collection of strong examples of major methods for I / O files.

Open a File

Syntax

The method to open a file in asynchronous mode is syntaxed below –

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

Parameter Value

Here is the description of the parameters to be used –

Parameter Description
Path− This is a string that has the name of the file including route.
Flags − Flags display the actions of the file you want to open. All possible values are shown below.
Mode − Sets file mode (permit and sticky bits) but only when the file has been developed. It stands at 0666, readable and writable by nature.
Callback − This function gets two arguments (err, fd)
Flags

The read / write flags are-

Sr.No. Flag & Description
1 r
Open to read paper. There is an exception when the file doesn't exist..
2 r+
Open read and write paper. There is an exception when the file doesn't exist.
3 rs
Open file for synchronous reading.
4 rs+
Open read and write file, telling the OS to access it synchronously. See the 'rs' section on using this with caution.
5 w
Open writable paper. The file is generated (if there is no such file) or truncated (if there is).
6 wx
Like 'w' but fails when there's a Path.
7 w+
Open read and write paper. The file is generated (if there is no such file) or truncated (if there is).
8 wx+
Unlike 'w+,' even if route does exist, it fails.
9 a
Open the appended tab. If it doesn't exist the file will be generated.
10 ax
Like 'a' but fails when there's a route.
11 a+
Open Read and Append page. If it doesn't exist the file will be generated.
12 ax+
Like 'a+,' but fails when the path is in place.
Example

Let's create a js file named main.js with the following code to open a file named input.txt.


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!");     
});

Run main.js now to see the result –

$ node main.js
Verify the Output
Going to open file!
File opened successfully!

Get File Information

Syntax

Following is the method syntax for obtaining information on a file –

fs.stat(path, callback)

Parameter Value

The description of the parameters is used here-

Parameter Description
Path− This is a string that has the name of the file including path.
Callback− This is a callback function that gets two arguments (err, stats) where the stats is an object of type fs. Stats printed in the example below. Besides the important attributes printed below in the example, several useful methods are available in the fs. Stats class which can be used to check the type of file. Those methods are given in the table below.
Sr.No. Method & Description
1 stats.isFile()
Returns true if a simple file type is given.
2 stats.isDirectory()
Returns true if a directory is type of file.
3 stats.isBlockDevice()
Returns true if a block device is in a file type.
4 stats.isCharacterDevice()
Returns true if a character device type is in the file.
5 stats.isSymbolicLink()
Returns true if symbolic link type of file.
6 stats.isFIFO()
Returns true if a FIFO is file type.
7 stats.isSocket()
Returns true if Asocket type of file is used.
Example

Let's create a Js file named main.js with the 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());    
});

Run main.js now to see the result –

$ node main.js
Verify the Output
Going to get file info!
{
dev: 1792,
mode: 33188,
nlink: 1,
uid: 48,
gid: 48,
rdev: 0,
blksize: 4096,
ino: 4318127,
size: 97,
blocks: 8,
atime: Sun Mar 22 2015 13:40:00 GMT-0500 (CDT),
mtime: Sun Mar 22 2015 13:40:57 GMT-0500 (CDT),
ctime: Sun Mar 22 2015 13:40:57 GMT-0500 (CDT)
}
Got file info successfully!
isFile ? true
isDirectory ? false

Writing a File

Syntax

The syntax of one of the methods to write to a file follows –

fs.writeFile(filename, data[, options], callback)

If the file already exists this method will overwrite the file. If you want to write to an existing file then use another available method.

Parameter Value

The description of the parameters is used here-
Parameter Description
Path− This is a string that has the name of the file including path.
Data− This is the string or buffer that should be written to the file.
Options− The third parameter will be an object that holds {encoding, mode, flag}. Default. Encoding is utf8, mode 0666 is octal. And the flag is 'w'.
callback − This is the callback function that gets a single error parameter that returns an error in the event of a write error.
Example

Let's create a file called main.js which has the following code –


var fs = require("fs");
console.log("Going to write into existing file");
fs.writeFile('input.txt', Keep Learning Keep Training!', function(err) {
if (err) {
return console.error(err);
}
console.log("Data written successfully!");
console.log("Let's read newly written data");
fs.readFile('input.txt', function (err, data) {
if (err) {
return console.error(err);
}
console.log("Asynchronous read: " + data.toString());
});
});

Run main.js now to see the result –

$ node main.js
Verify the Output
Going to write into existing file
Data written successfully!
Let's read newly written data
Asynchronous read: Keep Learning Keep Training!

Reading a File

Syntax

The syntax of one of the methods to be read from a file follows –

fs.read(fd, buffer, offset, length, position, callback)

This method is used to read the file using file descriptor. If you want to read the file using the file name directly, then you should use another available method.

Parameter Value

Parameter Description
FD− The descriptor file returned by fs.open() is this.
Puffer − This is the buffer to which the data is being written.
Offset − This is an offset to start writing on in the buffer.
Length − This is an integer which indicates the number of bytes to be read.
Position − This is an integer which specifies where the file should start reading from. If position is null, the current file positivates the data.
Callback − This is the three arguments callback function (err, bytesRead, buffer).
Example

Let's create a Js file named main.js with the code –


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());
}
});
});

Run main.js now to see the result –

$ node main.js
Verify the Output
Going to open an existing file
File opened successfully!
Going to read the file
97 bytes read
Keep Training and keep Learning
Until you get it Right !!!!!

Closing a File

Syntax

The syntax follows to close an opened file –

fs.close(fd, callback)

Parameter Value

The description of the parameters is used here-

Parameter Description
FD − This is the descriptor file returned using the file method fs.open().
Callback − This is a callback function There are no arguments other than a possible exception to the callback completion.
Example

Let's create a file called main.js which has the following code –


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);
}

// Print only read bytes to avoid junk.
if(bytes > 0) {
console.log(buf.slice(0, bytes).toString());
}

// Close the opened file.
fs.close(fd, function(err) {
if (err) {
console.log(err);
} 
console.log("File closed successfully.");
});
});
});

Run main.js now to see the result –

$ node main.js
Verify the Output
Going to open an existing file
File opened successfully!
Going to read the file
Keep Training and keep Learning
Until you get it Right !!!!!
File closed successfully

Truncate a File

Syntax

The method to truncate an opened file is syntaxed below-

fs.ftruncate(fd, len, callback)

Parameter Value

The description of the parameters is used here-

Parameter Description
FD − The descriptor file returned by fs.open() is this.
Len − This is the length of the file the file is truncated after.
Callback − This is a callback function There are no arguments other than a possible exception to the callback completion.
Example

Let's create a file called main.js which has the following code –


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 truncate the file after 10 bytes");

// Truncate the opened file.
fs.ftruncate(fd, 10, function(err) {
if (err) {
console.log(err);
} 
console.log("File truncated successfully.");
console.log("Going to read the same file"); 
fs.read(fd, buf, 0, buf.length, 0, function(err, bytes){
if (err) {
console.log(err);
}
// Print only read bytes to avoid junk.
if(bytes > 0) {
console.log(buf.slice(0, bytes).toString());
}
// Close the opened file.
fs.close(fd, function(err) {
if (err) {
console.log(err);
} 
console.log("File closed successfully.");
});
});
});
});

Run main.js now to see the result –

$ node main.js
Verify the Output
Going to open an existing file
File opened successfully!
Going to truncate the file after 10 bytes
File truncated successfully.
Going to read the same file
Tutorials
File closed successfully.

Delete a File

Syntax

Following is a syntax of the file deletion method –

fs.unlink(path, callback)

Parameter Value

The description of the parameters is used here-

Parameter Description
Path − This is the name of the file, with path.
Callback − This is a callback function There are no arguments other than a possible exception to the callback completion.
Example

Let's create a file called main.js which has the following code –


var fs = require("fs");
console.log("Going to delete an existing file");
fs.unlink('input.txt', function(err) {
if (err) {
return console.error(err);
}
console.log("File deleted successfully!");
});

Run main.js now to see the result –

$ node main.js
Verify the Output
Going to delete an existing file
File deleted successfully!

Create a Directory

Syntax

The method to create a directory is syntaxed below –

fs.mkdir(path[, mode], callback)

Parameter Value

The description of the parameters is used here-

Parameter Description
Path − This is the name of the directory, with path.
Mode − This is the permission to set a directory. By default: 0777.
Callback − This is a callback function There are no arguments other than a possible exception to the callback completion.
Example

Let's create a file called main.js which has the following code –


var fs = require("fs");
console.log("Going to create directory /tmp/test");
fs.mkdir('/tmp/test',function(err) {
if (err) {
return console.error(err);
}
console.log("Directory created successfully!");
});

Run main.js now to see the result –

$ node main.js
Verify the Output
Going to create directory /tmp/test
Directory created successfully!

Read a Directory

Syntax

The syntax of the method for reading a directory follows –

fs.readdir(path, callback)

Parameter Value

The description of the parameters is used here-

Parameter Description
Path − This is the name of the directory, with path.
Callback − This is a callback function that gets two arguments (err, files) where files are an array of file names excluding '.' and '..' in the directory.
Example

Let's create a file called main.js which has the following code –


var fs = require("fs");
console.log("Going to read directory /tmp");
fs.readdir("/tmp/",function(err, files) {
if (err) {
return console.error(err);
}
files.forEach( function (file) {
console.log( file );
});
});

Run main.js now to see the result –

$ node main.js
Verify the Output
Going to read directory /tmp
ccmzx99o.out
ccyCSbkF.out
employee.ser
hsperfdata_apache
test
test.txt

Remove a Directory

Syntax

Following is the method syntax for deleting a directory –

fs.rmdir(path, callback)

Parameter Value

The description of the parameters is used here-

Parameter Description
Path − This is the name of the directory, with path.
Callback − This is a callback function There are no arguments other than a possible exception to the callback completion.
Example

Let's create a file called main.js which has the following code –


var fs = require("fs");
console.log("Going to delete directory /tmp/test");
fs.rmdir("/tmp/test",function(err) {
if (err) {
return console.error(err);
}
console.log("Going to read directory /tmp");
fs.readdir("/tmp/",function(err, files) {
if (err) {
return console.error(err);
}
files.forEach( function (file) {
console.log( file );
});
});
});

Run main.js now to see the result –

$ node main.js
Verify the Output
Going to read directory /tmp
ccmzx99o.out
ccyCSbkF.out
employee.ser
hsperfdata_apache
test.txt

No Sidebar ads