Web Programming TutorialsLearn How to Handle System Files in Node.JS

Learn How to Handle System Files in Node.JS

In the last article, we discussed the concept of streams in Node.js. In this article, we are going to discuss about file handling in node.js and the various operations on the file system along with the suitable examples.

Introduction to Node File System
In Node.js, we use the simple wrappers around standard POSIX functions in order to implement file I/O operations. The following is the syntax to import node file system module (fs).

var fs = require("fs")

Asynchronous vs Synchronous in Node.js File System module
In node.js file system (fs) module, every method has asynchronous as well as synchronous forms. In case of asynchronous forms, the first parameter is error and the last parameter is the completion callback function. It is advisable to use asynchronous method over synchronous method as the former never blocks a program while execution, but the latter does. Let us understand it with the help of the following example.

Step 1: – Create a file ‘inputData.txt’ inside the project ‘NodeFileSystemApplication’ with the following text details.

Hello!
Welcome to Eduonix tutorial for Node.js

Step 2: – Write the following code in the file ‘index.js. This example is demonstrating an asynchronous as well as a synchronous read for comparison.

var fs = require("fs");

// Example for the Asynchronous read
fs.readFile('inputData.txt', function (err, data) {
   if (err) {
      return console.error(err);
   }
   console.log("Result of the Asynchronous read: " + data.toString());
});

//Example for the Synchronous read
var data = fs.readFileSync('inputData.txt');
console.log("Result of the Synchronous read: " + data.toString());

console.log("Program has Terminated successfully");

Step 3: – After execution of the above program, we can observe the following output. Here, we can observe that the synchronous read is first displayed on the console followed by the asynchronous read as the former blocks a program while execution but the latter never blocks a program.

Result of the Synchronous read: 
Hello!
Welcome to Eduonix tutorial for Node.js
Program has Terminated successfully
Result of the Asynchronous read: 
Hello!
Welcome to Eduonix tutorial for Node.js

File operations in Node.js File System
Similar to the other programming languages, Node.js also perform the following file operations.

  • Open a file
  • Get file status and information
  • Write a file
  • Read a file
  • Close a file
  • Delete a file

Open a file in Node.js

We have to first import the ‘fs’ module and use the following method of the instance variable to open a file in an asynchronous mode.

var fs = require("fs");
fs.open(path, flags[, mode], callback);

Description of the parameters

  • path – this parameter represents the complete file path with type as string, which includes the path and the file name.
  • flags – this parameter indicates the behavior of the file that to be opened. The following are the possible values.

Flags

Description

r

This flag opens file for reading. It will throw an exception when the file does not exist.

r+

This flag opens file for reading and writing. It will throw an exception when the file does not exist.

rs

This flag opens file for reading in synchronous mode.

rs+

This flag opens file for reading and writing, asking the OS to open it synchronously.

w

This flag opens file for writing. It will create a file if it does not exist or truncated if the file exists.

wx

It is similar as that of flag ‘w’ but fails if the path exists.

w+

This flag opens a file for reading and writing. It will create a file if it does not exist or truncated if the file exists.

wx+

It is similar as that of flag ‘w+’ but fails if path exists.

a

This flag opens file for appending. It will create a file if it does not exist.

ax

It is similar as that of flag ‘a’ but fails if the path exists.

a+

This flag opens file for reading and appending. It will create a file if it does not exist.

  • mode – This parameter is used to set the file mode. It sets the permission and the sticky bits when the file is created. It default values are 0666, readable and writeable.
  • callback – This parameter represents the callback function which accepts the two arguments i.e. (error, data).

Example: – In the following example, we are going to open a file ‘newfile.txt’ for reading and writing.

var filesystem = require("fs");

// Asynchronous form to Open File
console.log ("We are opening a file!");
filesystem.open('newfile.txt', 'r+', function(error, data) {
   if (error) {
      return console.error(error);
   }
  console.log ("File has opened successfully!");     
});

Output
When we execute the above program, it will open the file in r+ mode and display the following on the console.

We are opening a file!
File has opened successfully!

Get file status and information
We have to first import the ‘fs’ module and use the following method of the instance variable to procure the information about a file.

var fs = require("fs");
fs.stat(path, callback);

Description of the parameters

  • path – This parameter represents the complete file path with type as string which includes the path and the file name.
  • callback − It is the callback function which accepts the two arguments i.e. (error, stats) where stats is an object of fs.Stats type. It has the following useful methods which can be used to check file type.

Method

Description

stats.isFile()

This method returns true if file type of a simple file.

stats.isDirectory()

This method returns true if file type of a directory.

stats.isBlockDevice()

This method returns true if file type of a block device.

stats.isCharacterDevice()

This method returns true if file type of a character device.

stats.isSymbolicLink()

This method returns true if file type of a symbolic link.

stats.isFIFO()

This method returns true if file type of a FIFO.

stats.isSocket()

This method returns true if file type of a socket.

Example: – In the following example, we are going to retrieve information about the file ‘inputData.txt’.

var filesystem = require("fs");

console.log ("We are opening a file!");
filesystem.stat ('inputData.txt', function (error, stats) {
   if (error) {
       return console.error(error);
   }
   console.log(stats);
   console.log ("File information retrieved successfully!");
   
   // Checking the file type
   console.log ("isFile ? " + stats.isFile());
   console.log ("isDirectory ? " + stats.isDirectory());  
   console.log ("isBlockDevice ? " + stats.isBlockDevice());
   console.log ("isCharacterDevice ? " + stats.isCharacterDevice());
   console.log ("isSymbolicLink ? " + stats.isSymbolicLink());
   console.log ("isFIFO ? " + stats.isFIFO());
   console.log ("isSocket ? " + stats.isSocket());
});

Output
When we execute the above program, it will retrieve the file information and display them on the console.

We are opening a file!
{ dev: -522563379,
  mode: 33206,
  nlink: 1,
  uid: 0,
  gid: 0,
  rdev: 0,
  blksize: undefined,
  ino: 28710447624959708,
  size: 47,
  blocks: undefined,
  atime: Tue Feb 28 2017 00:33:57 GMT-0500 (Eastern Standard Time),
  mtime: Sun Jan 01 2017 16:22:22 GMT-0500 (Eastern Standard Time),
  ctime: Tue Feb 28 2017 00:33:57 GMT-0500 (Eastern Standard Time),
  birthtime: Tue Feb 28 2017 00:33:57 GMT-0500 (Eastern Standard Time) }
File information retrieved successfully!
isFile ? true
isDirectory ? false
isBlockDevice ? false
isCharacterDevice ? false
isSymbolicLink ? false
isFIFO ? false
isSocket ? false

Writing data to a file in Node.js
We have to first import the ‘fs’ module and use the following method of the instance variable to write data to a file. This method will over-write the file if the file already exists.

var fs = require("fs");
fs.writeFile(filename, data[, options], callback);

Description of the parameters

  • path − This parameter represents the complete file path with type as string which includes the path and the file name.
  • data – This parameter represents the actual data in the type of String or Buffer to be written into the file.
  • options – The options parameter is an object that holds details about encoding, mode, and flag. By default the values of encoding is utf8, mode is octal value 0666, and flag is ‘w’.
  • callback − It is the callback function, which accepts a single parameter error that returns an error when any writing error is encountered.

Reading data from a file in Node.js
We have to first import the ‘fs’ module and use the following method of the instance variable to read the data from a file.

var fs = require("fs");
fs.read(fd, buffer, offset, length, position, callback);

Description of the parameters

  • fd – This parameter is the file descriptor which is returned by filesystem.open() method.
  • buffer − This parameter is the buffer where the data will be written to.
  • offset − This parameter is the offset in the buffer that defines where to start writing.
  • length – This parameter is an integer that specifies the number of bytes which is to be read.
  • position – This parameter is an integer that specifies where to begin reading from in the file. If position is null, then the data will be read from the current file position.
  • callback − This parameter is the callback function which accepts the following three arguments. They are error, bytesRead, and buffer.

Example: – In the following example, we are going to write data to the file ‘inputNewData.txt’ and read this file data by using two read methods i.e. readFile and read.

var filesystem = require("fs");

console.log ("We are opening a file!");
filesystem.writeFile('inputNewData.txt', 'Studying File Handling in Node.js!',  function(error) {
   if (error) {
      return console.error(error);
   }
   
   console.log ("Data successfully written to a file!");
   console.log ("Reading the recently written file data!");
   filesystem.readFile('inputNewData.txt', function (error, data) {
      if (error) {
         return console.error(error);
      }
      console.log("Result of the Asynchronous read: " + data.toString());
   });
});

/// Using Read Method
var buf = new Buffer(1024);

filesystem.open('inputNewData.txt', 'r+', function(err, fd) {
	   if (err) {
	      return console.error(err);
	   }
	   console.log("File opened successfully!");
	   console.log("We are now reading the file");
	   filesystem.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("Displaying bytes data on the screen " + buf.slice(0, bytes).toString());
	      }
	   });
	});

Output
When we execute the above program, it will read the file data and display them on the console as shown below.

We are opening a file!
File opened successfully!
We are now reading the file
33 bytes read
Displaying bytes data on the screen Studying File Handling in Node.js!
Data successfully written to a file!
Reading the recently written file data!
Result of the Asynchronous read: Studying File Handling in Node.js!

Closing a file in Node.js
We have to first import the ‘fs’ module and use the following method of the instance variable to close a file.

var fs = require("fs");
fs.close(fd, callback);

Description of the parameters

  • fd − This parameter represents the file descriptor which is returned by filesystem.open() method.
  • callback − This parameter represents a callback function, which accepts a single error argument to return the error details in case of an exception.

Example: –In the following example, we are going to retrieve information about the file ‘inputData.txt’.

var filesystem = require("fs");

console.log("Going to open an existing file");
filesystem.open('inputData.txt', 'r+', function(error, fd) {
   if (error) {
      return console.error(error);
   }
   console.log("File has opened successfully!");

      // Close the opened file.
   filesystem.close(fd, function(error){
         if (error){
            console.log(error);
         } 
         console.log("File has been closed successfully.");
      });
   });

Output
When we execute the above program, it will first open an existing file and then close that file.

Going to open an existing file
File has opened successfully!
File has been closed successfully.

Delete a file in Node.js
We have to first import the ‘fs’ module and use the following method of the instance variable to close a file.

var fs = require("fs");
fs.unlink(path, callback);

Description of the parameters

  • path − This parameter represents the complete file path with type as string, which includes the path and the file name.
  • callback − This parameter represents a callback function which accepts a single error argument to return the error details in case of an exception.

Example: – In the following example, we are going to delete a file ‘output.txt’.

var filesystem = require("fs");

console.log("We are going to delete an existing file output.txt");
filesystem.unlink('output.txt', function(error) {
   if (error) {
      return console.error(error);
   }
   console.log ("File has been deleted successfully!");
});

Output
When we execute the above program, it will delete an existing file.

We are going to delete an existing file output.txt
File has been deleted successfully!

Conclusion: –
In this article, we discussed about the file system in Node.js. Here, we have covered various file handling operations such as opening a file, reading the file status information, write and read file operations, closing a file and deleting a file in Node.js.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Exclusive content

- Advertisement -

Latest article

21,501FansLike
4,106FollowersFollow
106,000SubscribersSubscribe

More article

- Advertisement -