DEV Community

Cover image for Efficiently Listing Files using the File System Module in Node.js
Subham
Subham

Posted on

Efficiently Listing Files using the File System Module in Node.js

Hi, I'm Subham Maity, a software engineer. I also enjoy teaching others how to code through my tutorials. I'm always eager to learn new things and share my knowledge with the community.

⚡ I recently wrote an article on A Beginner’s Guide to Efficiently Listing Files using the File System Module in Node.js and wanted to share it with you all. You can find the article on my website https://codexam.vercel.app/docs/node/node1 [Better View]

⚡ I also have a repository on GitHub where you can find all the code and projects related to this topic. You can find the repository at https://github.com/Subham-Maity/node-js-full-stack-tutorial

❗ For a more in-depth look at this topic, including a detailed table of contents, check out the complete tutorial on my GitHub Repo

If you want to stay updated with my latest projects and articles, you can follow me on:

Github

Instagram

YouTube

LinkedIn

Twitter

Tutorial Website

Creating files dynamically in a folder is a common task in web development, and Node.js offers an easy way to achieve this using the fs module. In this article, we will explore how to create files in a folder using Node.js.

⭐ Files Creation

Problem Statement : Make files in a folder

  1. Create a folder named files in the root directory of your project.

making a simple file is very easy just use the fs module and call the writeFileSync method and pass the file name and the data you want to write in the file as the parameters.

const fs = require('fs');
fs.writeFileSync('hello.txt', 'Hello World!');
Enter fullscreen mode Exit fullscreen mode
  1. Now do like this
const fs = require('fs');
const path = require('path');
const dirPath = path.join(__dirname, 'files');//__dirname will give the current directory name and files is the folder name

    //console.warn(dirPath);//this will print the path of the folder

    for (i = 0; i < 10; i++) {

    //fs.writeFileSync("hello.txt", "Hello World!");
    //this will create a file named hello.txt in the root directory and overwrite it if it already exists
    //So we need to add dirPath in the file name and make it dynamic like text1.txt,text2.txt,text3.txt etc

        fs.writeFileSync(dirPath + `/file${i}.txt`, `Hello World! ${i}`);

     //fs.writeFileSync(dirPath + `/file'+i+'.txt`, `Hello World!`+i);//this will also work
    }
Enter fullscreen mode Exit fullscreen mode

Now run node index.js and check the files folder. You should see 10 files with the names file0.txt to file9.txt and the contents Hello World! X, where X is the current value of i.

Code Explanation

Step 1

const fs = require('fs');

  • The fs module is used to interact with the file system in Node.js.

Step 2

const path = require('path');

  • The path module provides utilities for working with file and directory paths.

Step 3

const dirPath = path.join(__dirname, 'files');

  • The __dirname variable is a special variable in Node.js that represents the directory name of the current module.
  • The path.join() method joins all given path segments together using the platform-specific separator as a delimiter, then normalizes the resulting path.
  • In this case, we're joining the current directory name with a subdirectory called "files".

Step 4

for (i = 0; i < 10; i++) {

  • This is a for loop that will run 10 times.

Step 5

fs.writeFileSync(dirPath + `/file${i}.txt`, `Hello World! ${i}`);

  • The fs.writeFileSync() method writes data to a file, replacing the file if it already exists.

  • In this case, we're writing a file to the "files" subdirectory with a filename of "fileX.txt", where X is the current value of i.

  • The contents of each file will be "Hello World! X", where X is the current value of i.

Problem Statement : We need to see the files in the folder

3 . We are going to use readdir

fs.readdir(dirPath, (err, files) => {
     if (err) {
         console.error(err);
         return;
     }
     console.warn(files);
   });
Enter fullscreen mode Exit fullscreen mode

Output

   [ 'file0.txt',
    'file1.txt',
    'file2.txt',
    'file3.txt',
    'file4.txt',
    ]
Enter fullscreen mode Exit fullscreen mode

Code Explanation

fs.readdir(dirPath, (err, files) - The fs.readdir() method reads the contents of a directory.

  • In this case, we're reading the contents of the "files" subdirectory.
  • The files parameter is an array of filenames in the directory.
  • The err parameter is an error object if an error occurred, or null if no error occurred

console.warn(files); - This will print the array of filenames to the console.

Problem Statement : We don't want to see the files in the array format

  1. We are going to use the forEach method to iterate over the array and print the files

forEach is a method that is used to iterate over an array.

Syntax

    arr.forEach(abc => {
        console.warn(abc);
    });
Enter fullscreen mode Exit fullscreen mode

or

    arr.forEach((abc, index) => {
        console.warn(index, abc);
    });
Enter fullscreen mode Exit fullscreen mode
    fs.readdir(dirPath, (err, files) => {
        if (err) {
            console.error(err);
            return;
        }
        files.forEach(file => {
            console.warn(file);
        });
    });
Enter fullscreen mode Exit fullscreen mode

or

    fs.readdir(dirPath, (err, files) => {
        if (err) {
            console.error(err);
            return;
        }
        files.forEach((file, index) => {
            console.warn(index, file);
        });
    });
Enter fullscreen mode Exit fullscreen mode

Output

    file0.txt
    file1.txt
    file2.txt
    file3.txt
    ...this will go on
Enter fullscreen mode Exit fullscreen mode

Code Explanation

files.forEach(file => { - This is a forEach loop that will iterate over the array of filenames.

console.warn(file); - This will print the filename to the console.

Top comments (0)