File System- Node Js

Node implements File I/O using simple wrappers around standard POSIX functions. 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 an error. It is better to use an asynchronous method instead of the asynchronous method, as the former never blocks a program during its execution, whereas the second one does.

Example

Create a text file named input.txt with the following content −

Tutorials Point is giving self learning content
to teach the world in simple and easy way!!!!!

Let us create a js file named main.js with the following 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");

Now run the main.js to see the result −

$ node main.js

Verify the Output.

Synchronous read: Tutorials Point is giving self learning content
to teach the world in simple and easy way!!!!!

Program Ended
Asynchronous read: Tutorials Point is giving self learning content
to teach the world in simple and easy way!!!!!

The following sections in this chapter provide a set of good examples on major File I/O methods.

Open a File

Syntax

Following is the syntax of the method to open a file in asynchronous mode −

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

Parameters

Here is the description of the parameters used −

  • path − This is the string having file name including path.
  • flags − Flags indicate the behavior of the file to be opened. All possible values have been mentioned below.
  • mode − It sets the file mode (permission and sticky bits), but only if the file was created. It defaults to 0666, readable and writeable.
  • callback − This is the callback function which gets two arguments (err, fd).

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);
   }
   console.log("File opened successfully!");     
});

Now run the main.js to see the result −

$ node main.js

Verify the Output.

Going to open file!
File opened successfully!

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.No. Method & Description
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 asocket.

Example

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

Now run the main.js 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

Following is the syntax of one of the methods to write into a file −

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

This method will overwrite the file if the file already exists. If you want to write into an existing file then you should use another method available.

Parameters

Here is the description of the parameters used −

  • path − This is the string having the file name including path.
  • data − This is the String or Buffer to be written into the file.
  • options − A third parameter is an object which will hold {encoding, mode, flag}. By default. encoding is utf8, mode is octal value 0666. and the flag is ‘w’
  • callback − This is the callback function that gets a single parameter err that returns an error in case of any writing error.

About Author

Leave a Reply

Your email address will not be published. Required fields are marked *

PAGE TOP
error

Enjoy this blog? Please spread the word :)

RSS
Follow by Email