• Node.js Video Tutorials

Node.js - File System



The Node.js API is a server-side programming technology. Hence, a Node.js application may be required to interact with the physical file system of the server. The Node.js API includes fs module that enables the developer to perform read/write operations on disk files. The fs module in Node.js provides synchronous as well as asynchronous methods for file handling.

To use the filesystem functions, you need to import the fs module using the following syntax −

var fs = require("fs")

Synchronous vs Asynchronous

Every method in the fs module has synchronous as well as asynchronous version. Asynchronous methods take the last parameter as the completion function callback and the first parameter of the callback function as error.

For example, the synchronous method for writing data in a file is −

fs.writeFileSync(file, data[, options])

On the other hand, its asynchronous version has the following syntax −

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

The asynchronous methods are non-blocking in nature as compared to the synchronous methods.

For the example codes in this chapter, we shall use 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!!!!!

Writing a file

The following program shows how to write data in a file with synchronous as well as asynchronous methods.

const fs = require('fs');
var text = `Tutorials Point is giving self learning content
to teach the world in simple and easy way!!!!!
`;

console.log("Writing synchronously");
fs.writeFileSync("input.txt", text);

console.log("Writing asynchronously");
fs.writeFile('input.txt', text, function (err) { 

   if (err)
      console.log(err);
   else
      console.log('Write operation complete.');
});

Output

Writing synchronously
Writing asynchronously
Write operation complete.

Reading a file

The ReadFile() method in fs module reads a file asynchronously. It has the following syntax −

fs.readFile(fileName [,options], callback)

On the other hand, the ReadFileSync() method is its synchronous version, with the following syntax −

fs.readFileSync(fileName [,options])

Example

The following program reads the input.txt file synchronously as well as asynchronously.

const fs = require('fs');

console.log("Reading synchronously");
data = fs.readFileSync("input.txt");
console.log(data.toString());

console.log("Reading asynchronously");
fs.readFile('input.txt', function (err, data) {
   if (err) {
      return console.error(err);
   }
   console.log("Asynchronous read: " + data.toString());
});
console.log('Read operation complete.');

Output

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

Reading asynchronously
Read operation complete.
Asynchronous read: Tutorials Point is giving self learning content
to teach the world in simple and easy way!!!!!

Open a file

The readFile() and writeFile() method open and close the file to be read/written implicitly. Instead, you can explicitly open a file, set the file opening mode indicating whether to use it for reading or writing, and then close the file.

The open() method has the following signature −

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

Parameters

  • 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).

The values of flag parameter 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.

Let us open a file “input.txt” for writing data into it.

const fd = fs.open('input.txt', 'w', (err, fd) => {
   if (err) {
      console.log(err);
      return;
   }
});

To open() method returns a reference to the file, called as File Descriptor. A file descriptor is a unique integer, and used as an argument for the methods performing write and read operations.

The write() method in fs module saves data into the file referred to by the file descriptor that the open() method returns.

write(fd, string[, position[, encoding]], callback)

Parameters

  • fd − The file descriptor

  • string − the data to be written

  • position − to start writing from Default: null

  • encoding − character encoding string Default: 'utf8'

  • callback − The callback function to be invoked.

Following snippet writes the given text into the file we have opened above.

var data = `Tutorials Point is giving self learning content
to teach the world in simple and easy way!!!!!
`;

if (err) {
   console.log(err);
   return;
}

It is always recommended to close the opened file, especially if opened in writable mode.

// Close the file
fs.close(fd, (err) => {
   if (err) {
      console.log(err);
      return;
   }
});

Let us put all these snippets together as a program to open a file in writable mode, put some data in it, and close it.

Example

const fs = require('fs');

// Open a file for writing
const fd = fs.open('input.txt', 'w', (err, fd) => {
   if (err) {
      console.log(err);
      return;
   }

   // Write some data to the file
   var data = `Tutorials Point is giving self learning content
   to teach the world in simple and easy way!!!!!
   `;

   fs.write(fd, data, (err) => {
      if (err) {
         console.log(err);
         return;
      }

      // Close the file
      fs.close(fd, (err) => {
         if (err) {
            console.log(err);
            return;
         }

         console.log('The file was written successfully!');
      });
   });
});

When executed, the above program causes input.txt created in the current directory.

To read back the file, it must be opened in read mode. The read() method in fs module uses the file descriptor and retrieves the data in it in a buffer object.

read(fd, buffer[, options], callback)

Parameters

  • fd − file descriptor

  • buffer − The buffer that the data will be written to.

  • options − offset, length and position

  • callback − function to be invoked.

To read back the data in input.txt, use the read() method as follows −

Example

var fs = require('fs');

fs.open('test.txt', 'r', function (err, fd) {
    
   if (err) {
      return console.error(err);
   }
    
   var buffr = Buffer.alloc(1024);
    
   fs.read(fd, buffr, function (err) {
       
      if (err) throw err;
         else
      console.log(buffr.toString());
   });
        
   // Close the opened file.
   fs.close(fd, function (err) {
      if (err) throw err;
   });
});

Run the above program. Contents of your input.txt will be retrieved and displayed on the console.

Promises API

In a Node.js application, there may be a large number of nested callbacks if it is required to perform many different activities asynchronously. However, the code then can become disorganized, commonly called callback hell. To overcome this problem, JavaScript introduced the concept of promises.

A promise is essentially an improvement of callbacks that perform asynchronous tasks. It represents an activity that will either be completed or declined. If the promise is fulfilled, it is resolved; otherwise, it is rejected. Promises, unlike typical callbacks, may be chained.

In the versions of Node.js after version 10, the fs module contains file management method that implement promise concept. (The Callback and synchronous methods are also present).

The new asynchronous functions use async/await syntax. The function is prefixed with async keyword and it always returns a promise. The keyword await makes JavaScript wait until that promise settles and returns its result.

The Promises API version of writeFile() method in fs module is as follows −

fsPromises.writeFile(file, data[, options])

Parameters

  • file − filename or FileHandle

  • data − string or Buffer. The method returns a Promise object. It asynchronously writes data to a file, replacing the file if it already exists. data can be a string, or a buffer.

The following program uses the Promisified writeFile() method.

Example

const fs = require("fs");
var data = `Tutorials Point is giving self learning content
to teach the world in simple and easy way!!!!!
`;
async function write_file() {
   await fs.promises.writeFile("input.txt", data);
   console.log("Data written successfully");
}

write_file();

On the other hand, the readFile() method in the Promises API has following syntax −

fsPromises.readFile(path[, options])#

Parameters

  • path − filename or FileHandle

  • options include encoding, flag, signal

The method returns − a Promise. It asynchronously reads the entire contents of a file.

Example

const fs = require("fs");

async function read_file() {
   const secret = await fs.promises.readFile("input.txt");
   console.log(secret.toString());
}

read_file();

To retrieve the contents of the file (input.txt), save the above code and run from command line.

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

Closing a File

Syntax

Following is the syntax to close an opened file −

fs.close(fd, callback)

Parameters

Here is the description of the parameters used −

  • fd − This is the file descriptor returned by file fs.open() method.

  • callback − This is the callback function No arguments other than a possible exception are given to the completion callback.

Example

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

Now run the main.js to see the result −

$ node main.js

Verify the Output.

Going to open an existing file
File opened successfully!
Going to read the file
Tutorials Point is giving self learning content
to teach the world in simple and easy way!!!!!

File closed successfully.

Truncate a File

Syntax

Following is the syntax of the method to truncate an opened file −

fs.ftruncate(fd, len, callback)

Parameters

Here is the description of the parameters used −

  • fd − This is the file descriptor returned by fs.open().

  • len − This is the length of the file after which the file will be truncated.

  • callback − This is the callback function No arguments other than a possible exception are given to the completion callback.

Example

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

Now run the main.js 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 the syntax of the method to delete a file −

fs.unlink(path, callback)

Parameters

Here is the description of the parameters used −

  • path − This is the file name including path.

  • callback − This is the callback function No arguments other than a possible exception are given to the completion callback.

Example

Let us create a js file named main.js having 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!");
});

Now run the main.js to see the result −

$ node main.js

Verify the Output.

Going to delete an existing file
File deleted successfully!

Create a Directory

Syntax

Following is the syntax of the method to create a directory −

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

Parameters

Here is the description of the parameters used −

  • path − This is the directory name including path.

  • mode − This is the directory permission to be set. Defaults to 0777.

  • callback − This is the callback function No arguments other than a possible exception are given to the completion callback.

Example

Let us create a js file named main.js having 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!");
});

Now run the main.js to see the result −

$ node main.js

Verify the Output.

Going to create directory /tmp/test
Directory created successfully!

Read a Directory

Syntax

Following is the syntax of the method to read a directory −

fs.readdir(path, callback)

Parameters

Here is the description of the parameters used −

  • path − This is the directory name including path.

  • callback − This is the callback function which gets two arguments (err, files) where files is an array of the names of the files in the directory excluding '.' and '..'.

Example

Let us create a js file named main.js having 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 );
   });
});

Now run the main.js 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 syntax of the method to remove a directory −

fs.rmdir(path, callback)

Parameters

Here is the description of the parameters used −

  • path − This is the directory name including path.

  • callback − This is the callback function No arguments other than a possible exception are given to the completion callback.

Example

Let us create a js file named main.js having 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 );
      });
   });
});

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

Methods Reference

Advertisements