File System Module in Node JS

meghaghotkar

Megha Ghotkar

Posted on December 23, 2022

File System Module in Node JS

To handle the file operations like creating, reading, deleting files etc. Node JS provides an inbuilt module called fs (file system)
There is no need to install this module to use the file system module, as it is a build in module that comes with the node.js installation. we just need to import this using require () method
const fs =require(‘fs’);
File system has two forms depending upon user requirement
synchronous and asynchronous
Synchronous approach:
They are called blocking functions hence its block the next command from execution. It waits for each operation to complete, after that it executes the next operation.

Asynchronous approach:
They are called non-blocking functions hence it never waits for each operation to complete, rather it executes all operations in the first go itself.

Example for synchronous and asynchronous

First let’s create a text file named as an input.txt with the following contents:

Hi Megha, Welcome to the blog for File system module in Node JS.

Now create .ts file named as index.ts with the following code
Example for synchronous method

 var fs = require("fs");
const DataPath='./input.txt

// synchronous read
fs.readFileSync(DataPath, function (err:any, data:any) {
   if (err) {
      return console.error(err);
   }
   console.log("synchronous read: " + data.toString());
});
Enter fullscreen mode Exit fullscreen mode

Example for asynchronous method

var fs = require("fs");
const DataPath='./input.txt' 

// asynchronous read
fs.readFile(DataPath, function (err:any, data:any) {
   if (err) {
      return console.error(err);
   }
   console.log("Asynchronous read: " + data.toString());
});
Enter fullscreen mode Exit fullscreen mode

The ‘fs’ module provides us a multiple method
Common use for the file system module is to
• Open Files
• Read Files
• Create Files
• Update Files
• Delete Files
• Rename Files

Open a File:
If I just want to open the file then I will use fs.open()method.
fs.open(path, flags, mode, callback)

  • path:It holds the name of the file to read or the entire path if stroed at other locations
  • flags:(optional) flags indicate the behaviour of the file to be opened possible values(r, r+, rs, rs+, w, w+ etc)
  • mode:(optional)Sets the mode of file i.er-read, w-write It sets to default as readwrite.
  • callback:It’s a callback function. It takes two parameter
  • err:If any error occurs.
  • data:Contents of the file It is called after the open operation is executed.

First let’s create a text file named as a input.txt as I mentioned above with the following contents:
Hi Megha, Welcome to the blog for File system module in Node JS.
Now create .ts file named as index.ts with the following code

var fs = require("fs");
const DataPath='./input.txt' 
console.log("open file");
fs.open(DataPath,'r+',function(err:any){
   try{
      console.log("File open successfully")
   }
   catch(error){
      console.log("error occurred while opening file");
   }
});
Enter fullscreen mode Exit fullscreen mode

Reading a file:This method is used to read the file

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

  • fd:this is the file description returned by fs.open () method.
  • buffer:this is the buffer that the data will be written to.
  • offset:This is the offset in the buffer to start writing at.
  • length:this is an integer specifying the number of bytes to read.
  • position:This is an integer specifying where to begin reading from in the file. If the position is null, data will be read from the current file position.
  • callback:It’s a callback function that is called after reading of the file. It takes two parameters
  • err:If any error occurs.
  • data:Contents of the file.

  • Add following code to the index.ts file which we have created already

var fs = require("fs");
const DataPath='./input.txt' 
console.log("opening an existing file");
fs.open(DataPath, 'r+', function(err:any, fd:any) {
   if (err) {
      return console.error(err);
   }
   console.log("File opened successfully!");
   console.log("reading the file");

   fs.readFile(DataPath, function (err:any, data:any) {
         try{
         console.log( data.toString());
         }
         catch(error){
            console.log("error occured while fetching data")
          }
      });
});
Enter fullscreen mode Exit fullscreen mode

Writing to a file: this method will overwrite the file if the file already exists. Is used to write the specified data to a file . By default, the file would be replaced if it exists.

fs.writeFile(path, data, options, callback)

  • path: It holds the name of the file to read or the entire path if stroed at other locations
  • data: It is a string, TypedArray that will be written to the file
  • options: It’s a string that can be used to specify optional parameters. It has three optional parameter:
  • encoding: It’s a string value that speciifes the encoding of the file. The default value is ‘utf8’ .
  • mode: Its an integer value that specifies the file mode
  • flag: It’s a string value that speciifes the flag used while writing to the file. The default value is ‘w’.
  • callback: It’s a function that would be called when the method is executed
  • err: If any error occurs.
var fs = require("fs");
const DataPath='./input.txt' 

var data = "Hi Megha,Welcome to the blog for File system module in Node JS.";

fs.writeFile(DataPath, data, (err:any) => {
  if (err) console.log(err);
  console.log("Successfully Written to File.");
});
Enter fullscreen mode Exit fullscreen mode

Fs module is useful when you want perform an any Fileoperation on files.

💖 💪 🙅 🚩
meghaghotkar
Megha Ghotkar

Posted on December 23, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

File System Module in Node JS
fsmodule File System Module in Node JS

December 23, 2022