In node.js, why do we need File System Modules(fs)? the answer is simple whenever you need to deal with file operations like accessing the file from server, saving file to your server or into your local machine and many more operations are there, so to deal with these situations we have file system module known as ‘fs’ module which is by default package of node.js you do not need to install its package using ‘npm’.

In this tutorial, we are going to cover all the basic operations related to File system using ‘fs’ module of node.js.

Topics covered

  • File operations in node.js File System.
    • Open file – opens a file.
    • Get file Info – getting full information about the file.
    • Create and Write into a file – creating a single file and triggering write operation.
    • Read file – reading a single file.
    • Update file – updating the existing file.
    • Delete file – deleting a file.
  • Synchronous and Asynchronous.

File operations in node.js File System

Open file – opens a file

To perform any file system operation we first need to import file system modules, which can be done by using  require  function.

Syntax:

 var fs = require(‘fs’) 

Once you have done importing part all you need to do is call a function which will do you work so we are going to use ‘open()’ function using ‘fs’ instance.

Syntax:

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

Parameters:

From its syntax, it is cleared that it takes four parameters.

1. path – It contains the file name with a path to the file which you want to open.

2. flags[mode] – It defines the behavior of the file to be opened(eg r,r+,w,w+….).All the possible value mention in sub-topic ‘Flags’.

3. mode –  It defines the mode in which you want to open the file i.e. in readable mode or writable mode, but only if a file is created.It defaults to 0666, readable and writable.

4. callback –  It is call back function which takes two arguments(error, result).

Flags:
r Open a file in the readable mode for reading purpose.
r+ Open a file for both reading and writing purpose.
rs Open a file for reading purpose in synchronous mode.
rs+ Open a file for reading and writing and also asking the OS to open it in synchronous mode.
w Open a file for writing the only purpose. The file will be created (if it does not exist) or truncated (if it exists).
wx It is same as ‘w’ but fails if the path exists.It will not create the file if it doesn’t exist in a given path.
w+ Open a file for reading and writing purpose. The file will be created (if it does not exist) or truncated (if it exists).
wx+ It is same as ‘w’ but it will fail if a given path exists.
a It will Open a file for appending the more content in existing file. The file is created if it does not exist.
ax It will do same work like ‘a’ but will fail if the path exists.
a+ Open file for reading and appending operation. The file will be created if it doesn’t exist.
ax+ It is same as ‘a+’ but will fail if the path exists.

Example – In the following example, we are going to open a file ‘test.txt’ for reading purpose.

var fs = require('fs');
fs.open("./public/files/test.txt",'r',function(err,result){
if(err)
throw err;
else
console.log("File opened successfully");
});

Run command:

c:xyz\node> node test.js

Result:

File opened successfully!

 Get file Info – getting full information about file

Sometimes there is a situation when we need to know all the information about the file like its type, its birth time, its size and so on.To get the file info. ‘fs’ module contains function known as ‘stat()’ function which will give you all the information you need to know about the file.

 Syntax:

 fs.stat(path,callback)  

Parameters:

1.  path – It contains the file name with a path to the file which you want to open.

2. callback –  It is a callback function which takes two arguments(error, stats).

There are several methods available in fs.Stats class which can be used for different purposes and are given below with its description.

MethodDescription
stats.isFile() stats.isFile() returns true if the file type is a file.
stats.isDirectory() stats.isDirectory() returns true if the file type is a directory.
stats.isBlockDevice() stats.isBlockDevice() returns true if file type is a block device.
stats.isCharacterDevice() stats.isCharacterDevice()  returns true if file type is of a character device.
stats.isSymbolicLink() stats.isSymbolicLink() returns true if a file type is of symbolic link.
stats.isFIFO() stats.isFIFO() returns true if the file type is of  FIFO..
stats.isSocket() stats.isSocket() returns true if file type of a socket.

Now, you have gained enough information about ‘fs.stat()’ function so let’s implement it and see what we get.

Example:  In the following examples we are going to retrieve all the information about the file and also checking its type using stats() method.

var fs = require('fs');
console.log ("We are opening a file!");
fs.stat('./public/files/test.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());
});

Run Command:

c:xyz\node>node file_stat.js

Result:

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
}

Create and Write into a file – creating a single file and triggering write operation

In this section, we are going to create a text file and write our content into it.Again it is an operation which totally depends on file system module so we need to import ‘fs’ module first.But before we move towards its coding portion let’s first know its syntax, how many ways are there to create and write into the file and how to use it.

The file system module has the following method to create file and write contents into it

  1. fs.open()
  2. fs.writeFile()
  3. fs.append()

Let’s discuss it one by one.

1) fs.open() :

It is the same function which we have discussed earlier, we can use it to open a file in write mode and create our file by just passing its flag value as ‘w’ it will open the file for writing or it will create the file if gives file doesn’t exist.

Example: In below example, we are opening file ‘test2.txt’ and it will be created automatically since it is not available in given path. It will clear the concept of creating the file using ‘open()’.

var fs = require('fs');
fs.open('test2.txt', 'w', function (err, file) {
   if (err) throw err;
console.log(“File created successfully!”);
});

Run Command:

c:xyz\node>node create_file.js

Result:

File created successfully!

2) fs.writeFile():

The fs writeFile() method is used to create a file and also write our content into it at the same time.But if there will be any content in the file then, it will overwrite its content with the new given content.

Example: In the following example we are going to create one file ‘test_write.txt’ and at the same time we will be writing some content into it.

var fs = require('fs');
fs.writeFile('test_write.txt', 'Hello content!', function (err) {
if (err) throw err;
console.log('file created and Saved!');
});

Run Command:

c:xyz\node>node create_file.js

Result:

File created and Saved!

3) fs.appendFile():

The fs appendFile() method will append the content in the given file if the file doesn’t exist in the specified path the new file will automatically create and contents will get added to it.

Example: In the following example we are going to append some new content to the file which we have created earlier i.e ‘test_write.txt’.

var fs = require('fs');
fs.appendFile('test_write.txt', '\nI am xyz', function (err) {
if (err) throw err;
console.log('File created and Saved!');
});

Run Command:

c:xyz\node>node create_file.js

Result:

File created and Saved!

 Read file – reading a single file

We have learned earlier, how to create a file, but what is the use if we don’t know how to read a file.So in this section, we are going to learn all the syntaxes and methods required to perform the read operation in nodejs.

Syntax:

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

Parameters:

1. fd – It is a file descriptor returned by the fs.open() method.

2. buffer – It is a temporary storage known as the buffer where the data will be written to.

3. offset – It defines the offset in the buffer which tells where to start writing.

4. length – It is an integer type parameter which defines the number of bytes to be read.

5. position It is also an integer type parameter which specifies where to start reading from in the file.If the position is null, then the data will be read from the current file position.

6. callback –  It is call back function which takes three arguments(error, bytesRead, buffer).

Example: In the following example, we are going to read the content form the file which we created in the previous section.

var fs = require('fs');
 fs.readFile('test_write.txt','UTF-8', function(err, data) {
   if(err)
   throw err;

   console.log(data);
 });

Run Command:

c:xyz\node>node read_file.js

Result:

Hello content!
I am xyz

Update file – updating existing file

In this section, we are going to learn how to update an existing file. So what we are going is to pick a previously created file and update it with some more content using the following methods of fs module.

  1. fs.appendFile()
  2. fs.writeFile()

1) fs.appendFile() :

The fs appendFile() method will append or update the content in the given file if the file doesn’t exist in the specified path the new file will automatically get created and content will be added to it.

Example: In the following example we are going to append some new content to the file which we have earlier created i.e ‘test_write.txt’.

var fs = require('fs');
fs.appendFile('test_write.txt','\n Today is very beautiful day', function (err) {
 if (err) throw err;
 console.log('File updated and Saved!');
});

Run Command:

c:xyz\node>node update_file.js

Result:

File updated and Saved!

2) fs.writeFile():

The fs writeFile() method is to update and create a file, it also writes our content into it at the same time. But if there will be content in the fs writeFile() method will overwrite its content with the new given content.

Example: In the following example we are going to create one file ‘test_write.txt’ and at the same time writing some content into it.

var fs = require('fs');
fs.writeFile('test_write.txt', 'Hello content!', function (err) {
 if (err) throw err;
 console.log('File updated and Saved!');
});

Run Command:

c:xyz\node>node update_file.js

Result:

File updated and Saved!

Now to check whether your file contains data into it or not, just type the following cmd in your cmd terminal.

c:xyz\node>type test_write.txt  // type command is used to display text file content in console.
Hello content!

Delete file – deleting a file

In this section, we are going to learn how to delete an existing file. So we will pick a previously created file and then delete it using the ‘fs.unlink()’ methods of fs module.

Syntax:

 fs.unlink(path, callback) 

Parameters:

  1. path – It contains the file name with a path to the file which you want to open.
  2. callback –  It is a call back function which takes the single argument(error) to return the error generated during the execution process.

Example: In this example, we are going to delete our previously created file using ‘fs.unlink()’ method of ‘fs’ module.

var fs = require('fs');
fs.unlink('test_write.txt', function (err) {
if (err) throw err;
console.log('File deleted!');
});

Run Command:

c:xyz\node>node delet_file.js

Result:

File deleted successfully!

Synchronous and Asynchronous

In an asynchronous form, the method takes the last parameter as completion function callback and first parameter as the error.

It is always good to use an asynchronous method instead of synchronous because when we are developing production code, as it won’t block the event loop so you can build performant applications.

Example:

var fs = require("fs");
// Example for the Asynchronous read
fs.readFile('test_write.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('test_write.txt');
console.log("Result of the Synchronous read: " + data.toString());
console.log("Program has Terminated successfully");

Run Command:

c:xyz\node>node sync_async.js

Result:

Result of the Synchronous read:
I am xyz
Program has Terminated successfully
Result of the Asynchronous read:
I am xyz

Conclusion:

I hope everything that I explained is clear to you about the node.js file system and its operations.If you still have any problem then don’t hesitate to leave your comment below.

Learn More-