Node.js: File System - Day Five

File I/O is provided by simple wrappers around standard POSIX functions. To implement the files' I/O related operations, we are required to use the “fs” in built module in our application using the require operation. All the methods have asynchronous and synchronous forms.

In Node.js, we can perform the file I/O related operations in two ways, Synchronous and Asynchronous . In Node.js, each method has both forms. You can use any form depending upon your requirement.

Synchronous Methods

In Synchronous methods, there is not any concept of callback. When using the synchronous form, any exceptions are immediately thrown. We can use try/catch to handle the exceptions or allow them to bubble up.

Example: I have a text file that contains the following data.

text file

Now, I will read this file using synchronous and asynchronous method.
  1. var fs = require('fs');  
  2. var fileData = fs.readFileSync('file.txt');  
  3. //Synchronous Read  
  4. console.log("File Synchronous Read Start");  
  5. console.log( fileData.toString());  
  6. console.log("!! Finish");  
Output

Output

In this example, we implement the “fs” in built module and read the data of the text file using the “readFileSync” method. Name of “readFileSync” contains “Sync” postfix that indicates that file read operation is synchronous. Now, we read same file in asynchronous manner.

Asynchronous Method

The asynchronous method always takes a callback function as its last argument. The arguments passed to the callback function depend on the method, but the first argument is always reserved for an exception and second parameter is data or may be dependant upon method. If the operation was completed successfully, then the first argument will be null or undefined. Now, we read file in asynchronous manner.

Example
  1. var fs = require('fs');  
  2. //Asynchronous Read  
  3. console.log("File Asynchronous Read Start");  
  4. var fileData = fs.readFile('file.txt'function(error, data) {  
  5.     if (error) {  
  6.         return console.error(error);  
  7.     }  
  8.     console.log(data.toString());  
  9. });  
  10. console.log("!! Finish");  
Output

Output

Basic Operations in Files

Now, let's read the basic operations of file system like open, read, write, close, delete, truncate files.

Open File

In Node.js, we can use “open” method for opening a file in asynchronous or synchronous mode.

Syntax

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

Parameters
 
Parameter Description
Path Data type is string. Define the path of file that will be open
Flags Data type is string. Define the behavior of file to be opened.
Mode Data type is integer, define the permissions for file, but only if the file was created.
Callback Define callback function for method.

Flags

Flag Description
R Open file for reading. An exception occurs if the file does not exist.
r+ Open file for reading and writing. An exception occurs if the file does not exist.
rs+ Open file for reading and writing in synchronous mode.
W Open file for writing. The file is created (if it does not exist) or truncated (if it exists).
Wx Like 'w' but fails if path exists.
W+ Open file for reading and writing. The file is created (if it does not exist) or truncated (if it exists).
Wx+ Like 'w+' but fails if path exists.
A Open file for appending. The file is created if it does not exist.
Ax Like 'a' but fails if path exists.
A+ Open file for reading and appending. The file is created if it does not exist.
Ax+ Like 'a+' but fails if path exists.

Example

  1. var fs = require('fs');  
  2. console.log("file opened successfully!!");  
  3. fs.open('file.txt''r'function(error, data) {  
  4.     if (error) {  
  5.         console.log("Error occur");  
  6.     };  
  7.     console.log(data);  
  8. });  
  9. console.log("finish!!");  
Output

Output

Read File: Using “readFile” method, we can read the data from a file. The syntax of this method is given below.

Syntax

Fs.readFile(file[,option],callback)

Parameter
 
Parameters Description
File Filename or Descriptor name
Options Define encoding and flag, default value of encoding is “null” and default value of flag is “r”.
Callback Function call after completion of task, contain two parameter error and data.

Example

I have the following data into “file.txt” file.

data

Now, using the below code, I read the data from this file.

  1. var fs = require('fs');  
  2. //Asynchronous Read  
  3. console.log("File Asynchronous Read Start");  
  4. var fileData = fs.readFile('file.txt'"utf-8"function(error, data) {  
  5.     if (error) {  
  6.         return console.error(error);  
  7.     }  
  8.     console.log(data);  
  9. });  
  10. console.log("!! Finish");  
Output

Output

Write File: Using “writeFile” method we can write data into file. The syntax of this method is given below.

Syntax

Fs.writeFile(file, data[,options],callback)

Parameters
 
Parameter Description
Path Path of file
Data Data to written in file, data may be string or buffer
Options This parameter hold the encoding, flag and mode information, default value of encoding is “utf8”, flag is 0o666 and for mode is “w”.
Callback Function that will call after completion of task, this parameter contain single parameter error.

Example

  1. var fs = require('fs');  
  2. //Data for file  
  3. var data = "Write Line 1 \n Write Line 2 \n Write Line 3";  
  4. fs.writeFile("file.txt", data, function(error) {  
  5.     if (error) {  
  6.         console.log(error);  
  7.     }  
  8. });  
  9. console.log("Data Written Completed");  
  10. console.log("Read the Data");  
  11. fs.readFile("file.txt""utf-8"function(error, data) {  
  12.     if (error) {  
  13.         console.log(error);  
  14.     }  
  15.     console.log(data);  
  16. });  
Output

Output

Now, we check the data of “file.txt” file.

data

We can see that data is successfully written into file.

Append the Data

Using “fs.appendFile()” method, we can append the data into file.

Syntax

Fs.appendFile(file,data[,options],callback)

Parameters
 
Parameter Description
Path Path of file
Data Data to append in file, data may be string or buffer
Options This parameter hold the encoding, flag and mode information, default value of encoding is “utf8”, flag is 0o666 and for mode is “a”.
Callback Function that will call after completion of task, this parameter contain single parameter error.

Example

  1. var fs = require('fs');  
  2. //Data for file  
  3. fs.readFile("file.txt""utf-8"function(error, data) {  
  4.     if (error) {  
  5.         console.log(error);  
  6.     }  
  7.     console.log(data);  
  8.     console.log("Data Before Append");  
  9. });  
  10. var data = "Write Line 7 \n Write Line 8 \n Write Line 9";  
  11. fs.appendFile("file.txt", data, function(error) {  
  12.     if (error) {  
  13.         console.log(error);  
  14.     }  
  15. });  
  16. console.log("Data Written Completed");  
  17. console.log("Read the Data");  
  18. fs.readFile("file.txt""utf-8"function(error, data) {  
  19.     if (error) {  
  20.         console.log(error);  
  21.     }  
  22.     console.log(data);  
  23. });  
Output

Output

Get File Status

Using “fs.stat()” method, we can get file all file related information or some specific information.

Syntax: Fs.stat(file,callback)

Parameters
 
Parameter Description
File Path of file
Callback Function call after the completion of task, this function takes two parameter error and stat

Example

  1. var fs = require('fs');  
  2. //Data for file  
  3. fs.stat("file.txt"function(error, status) {  
  4.     if (error) {  
  5.         console.log(error);  
  6.     }  
  7.     console.log(status);  
  8. });  
Output

Output

In the above image, atime, mtime, and ctime define the access, modify, and change time.

“fs.stat()” method returns all the information related to file. We can also get type of file using the synchronous counterparts part of stat object.

Example
  1. var fs = require('fs');  
  2. //Data for file  
  3. fs.stat("file.txt"function(error, status) {  
  4.     if (error) {  
  5.         console.log(error);  
  6.     }  
  7.     console.log("isBlockDevice " + status.isBlockDevice());  
  8.     console.log("isCharacterDevice " + status.isCharacterDevice());  
  9.     console.log("isDirectory " + status.isDirectory());  
  10.     console.log("isFIFO " + status.isFIFO());  
  11.     console.log("isFile " + status.isFile());  
  12.     console.log("isSocket " + status.isSocket());  
  13.     console.log("isSymbolicLink " + status.isSymbolicLink());  
  14. });  
Output

Output

Delete File: Using “fs.unlink” file, we can delete a file.

Syntax

Fs.unlink(path, callback)
 
Parameter Description
File Path of file
Callback Function call after the completion of task, this function takes one parameter error

Example

  1. var fs = require('fs');  
  2. //Data for file  
  3. console.log("File to delete");  
  4. fs.unlink("file.txt"function(error) {  
  5.     if (error) {  
  6.         console.log(error);  
  7.     }  
  8.     console.log("file deleted Sucessfully");  
  9. });  
Output

Output

Close the file

Using “fs.close” method, we can close an opened file.

Syntax: Fs.close(fd,callback)

Parameter
 
Parameter Description
Fd Data type is integer, fd is file descriptor returned by fs.open() method
Callback Function executed after the completion of task, take one argument that is error.

Example

I have the following data into “file.txt” file.

data

Code to read this data is below.

  1. var fs = require('fs');  
  2. var Buffr = new Buffer(2048);  
  3. fs.open("file.txt""r"function(error, data) {  
  4.     if (error) {  
  5.         console.log(error);  
  6.     }  
  7.     console.log("File opened in raed mode");  
  8.     fs.read(data, Buffr, 0, Buffr.length, 0, function(eror, data_) {  
  9.         if (eror) {  
  10.             console.log(eror);  
  11.         }  
  12.         console.log(Buffr.slice(0, data_).toString());  
  13.         console.log("File Read Successfully");  
  14.     })  
  15.     fs.close(data, function(error_) {  
  16.         if (error_) {  
  17.             console.log(error_);  
  18.         }  
  19.         console.log("File Closed");  
  20.     })  
  21. })  
Output

Output

Today, we learned the basic file operations in Node.js. All these operations are asynchronous.  Node.js also provides the synchronous method for each operation. I hope you liked the article. Thanks for reading this article.

Up Next
    Ebook Download
    View all
    Learn
    View all