readFile() Vs readFileSync()

readFile() Vs readFileSync()

Holaa geeks !!
In this blog we'll see about file reading methods and the difference between readFile() and readfileSync() of node.js

Content
1. Overview of file reading  
2. readFile() vs readfileSync()
3. Conclusion

Lets get started!! 🎉


1. Overview

Reading a file is a common thing in every progrmming languages and every language has its own way of reading files. here.., in node we have File system module (fs) which allows us to work with files.

const fs=require('fs'); // imports file system module in variable fs

There are two types of reading files. They are buffer and streams.

  • Buffer reading

    The entire file will be read first and then the content will be delivered.

    • Methods: readFile() and readFileSync().
  • Stream reading

    Instead of reading the entire file at a time, it gets and delivers by a small chunks. This makes it time efficient.

    • Methods: readStream() .

2. readFile vs readFileSync

As i said before both readFile() and readFileSync() reads the file at once and then delivers the content.

The difference is that ,

  • readFile is non-blocking async.
  • readFileSync is blocking sync.

2.2 readFile()

const fs=require('fs');
 fs.readFile('test.txt','utf-8',(err,data)=>{  //utf decoding to avoid binary code output.
        if(err){
            console.log(err);
        }
        else{
            console.log(data);
        }
    });
    console.log(" -->The end<-- ");

Output:

'-->The end<--' 
Lorem ipsum dolor sit, amet consectetur adipisicing elit.
Repudiandae alias laborum,ut recusandae quibusdam fugit facere quis vero 
at quia illum dolore hic esse ipsa atque accusantium harum saepe eveniet.
  • Note:
    readFile() method uses a callback function. Due to its non-blocking nature, the program wont wait for the file to be read completely. So that the -->The end<-- message will be printed in first or in between the file content.

2.3 readFileSync()

const fs=require('fs');
var contents = fs.readFileSync('test.txt', 'utf8'); //utf decoding to avoid binary code output.
console.log(contents);
console.log(" -->The end<-- ");

Output:

Lorem ipsum dolor sit, amet consectetur adipisicing elit.
Repudiandae alias laborum,ut recusandae quibusdam fugit facere quis vero 
at quia illum dolore hic esse ipsa atque accusantium harum saepe eveniet.
'-->The end<--'
  • Note:
    readFileSync() method uses a variable to store the file content and then delivers it. Due to its blocking nature, the program waits till the file is read completely. So that the -->The end<-- message will be printed only after the content is delivered.

3. Conclusion

fileRead()fileReadSync()
Non-Blocking processBlocking process
Uses callbackuses variable to store content
Asynchronous natureSynchronous nature

Alright ppl hope it helped!, connect me📧 if any queries, thanks for reading! Stay tuned!! See yaa👋.