Node.JS also contains module that allows us to communicate with the file system. The FS module can be used to list files in directories, create new files in directories, stream files, video files, modify files permissions and etc.

Here we have two ways to read the content of directory synchronously, asynchronously and We are importing FS module into file using require function. Want to know further more about Require function, please do visit at require function in node js

What is Read Dir synchronously?

This method can be used read directory in synchronously. So let’s say we wanted to read the contents from a directory. we would start by creating the new file called list.js

//list.js

const fs = require("fs");

//read the file synchronously
console.log("Reading the file synchronously started");
const files = fs.readdirSync("./assets");
console.log(files);
console.log("Reading the file synchronously ends");

Before running it let’s create a folder namely assets into the same folder you are having the list.js file and put some files and folder into the asset folder similar the folder structure of mine.

(Figure 2: Folder structure)

Now i can read the content of a directory into a variable just by calling the readdirSync function.

(Figure 1: readdirSynchronously)

What is Read Dir Asynchronously?

This method works Asynchronously so it means order of code doesn’t matter and it works according the stack flow. So let’s take an example to understand it better. Now let’s say we wanted to read the contents from a directory asynchronously. Therefore we would start by creating the new file called listAsync.js

//listAsync.js

const fs = require("fs");

//read dir asyncronously
console.log("Reading the file asynchronously started");
fs.readdir("./assets", (err, files) => {
  if (err) {
    throw err;
  }
  console.log("Content in directory assets are:");
  console.log(files);
});
console.log("Reading the file asynchronously ends");

Now i can read the content of a directory into a callback function just by calling the readdir function.

(Figure 3: readdir)

Please do visit the official website for more information at https://nodejs.org/api/fs.html#fspromisesreaddirpath-options.

TaDa! it is done. Hope you find it helpful, Thank you for sticking till the end. Enjoy learning 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *