Fs module in node js (Asynchronous)

Fs module in nodejs (A synchronous version)

I would like to take you through the basics to understand asynchronous version of fs module. Let's see what are parameters & arguments.

Eg :function add (a,b){
            return a+b;
      }

 Here, a & b   are called parameters.

Eg : add (5,6) ; //calling a function
Here 5 & 6 are arguments.

So, in short parameters are given while defining the function & arguments are given while calling the function.

So we have understood parameter & arguments. Next, we will see what are higher order functions & callbacks.

When we pass a function as parameter to another function, the second function is called as a higher order function. The function passed as a parameter is called callback function. Now let's see how to use fs module in asynchronous version. In order to use modules in nodejs, we need to require it first.

const fs = require ("fs");

Let's Start playing with fs module.

To Create a new folder

fs.mkdir("Folder Name " ,() => {
       console. log ("Folder Created ");

});

The main difference between Synchronous and asynchronous is that we need to give a callback function in asynchronous version. The callback function here is an arrow function. The second difference is we don't need to write 'Sync' everywhere as we wrote in asynchronous version. I have already explained synchronous version in my last blog I will provide the link below.

To Create a new file file

fs.writeFile("Filename" ,"Text to be 
  written in file",()=>{
   console.log("File created");
});
The syntax will be same for all other operations. Like synchronous version while reading file we get buffer data in asynchronous version as well . So here also the second parameter will be encoding i.e " utf-8".I have memorized this way, that in synchronous we don't give any callbacks and in asynchronous we need to give callbacks. Now play around with file system in node.


Comments

Post a Comment

Popular posts from this blog

Fs module in node js!!!

Open source !!

Programming communities