List Files in Directory JavaScript with Examples

In this article, we will discuss the process of listing files in directory using JavaScript. From understanding the fundamentals to exploring practical examples.

When it involves to web development, managing files is a common task.

Whether you are required to display a list of files on your website, upload files from users, or process files on the server, JavaScript can be a powerful tool to finish these tasks.

Overview of JavaScript List Files in Directory

Before we proceed into the implementation details, let’s get a brief overview of what it means to list files in a directory using JavaScript.

Necessarily, it requires accessing the file system on the server or the client-side, retrieving the list of files present in a specific directory, and then displaying or performing actions with those files.

Understanding the JavaScript list files in directory

To list files in a directory, you must first understand the basics of file operations in JavaScript.

The language provides different methods and APIs that enable you to interact with files smoothly.

One of the most typically used APIs for file operations is the FileReader API.

It enables you to read the contents of files, making it an important component for listing files in a directory.

Here’s how you can use the FileReader API to get started:

const fileInput = document.getElementById('fileInput');

fileInput.addEventListener('change', (event) => {
  const fileList = event.target.files;

  for (const file of fileList) {
    console.log(file.name);
  }
});

In the example code, we have an input element with the ID “fileInput,” which enables the users to select files.

Then, we add an event listener to the input element, which triggers when the user selects one or more files.

The selected files are stored in the fileList object, and we can then loop through the list to access the details of each file, such as the file name.

Listing Files in a Directory Using JavaScript

Now that we have understood the basics, we will explore how to list files in a directory using JavaScript.

We will cover both server-side and client-side methods to cater to different cases.

Server-Side Approach with Node.js

When you are working on the server-side with Node.js, you can use the built-in fs module to handle file operations.

The fs.readdirSync method enables you to read the contents of a directory synchronously.

Here’s an example of how to list files in a directory using Node.js

const fs = require('fs');

const directoryPath = '/path/to/your/directory';

try {
  const files = fs.readdirSync(directoryPath);
  console.log(files);
} catch (error) {
  console.error('Error reading directory:', error);
}

In this example, replace ‘path/to/your/directory‘ with the actual path to the directory you want to list files from.

The fs.readdirSync method returns an array of file names present in the specified directory, which we then log to the console.

Client-Side Approach with HTML5 and JavaScript

On the client-side, you can use the File API provided by HTML5 to interact with files.

The FileReader API comes in handy when handling file operations, including listing files in a directory.

Here’s how you can list files in a directory using JavaScript and HTML5 on the client-side:

Here’s an example code:

<!DOCTYPE html>
<html>

<head>
  <title>List Files in a Directory javaScript</title>
</head>

<body>
  <input type="file" id="fileInput" multiple>
  <script>
    const fileInput = document.getElementById('fileInput');

    fileInput.addEventListener('change', (event) => {
      const fileList = event.target.files;

      for (const file of fileList) {
        // Process each file here
        console.log(file.name);
      }
    });
  </script>
</body>

</html>

In this client-side example, we have an input element of type “file” with the ID “fileInput“.

Users can choose multiple files using this input element. When the user selects files, the event listener attached to the input element triggers.

We can loop through the fileList to access the information of each file, including the file name.

Handling File Filters

Usually, you may only want to list files with specific extensions or add certain files from the listing.

Let’s explore how you can implement file filters in your file listing process.

Filtering Files by Extension

To filter files by extension, you need to verify the file name for the proper extension and include only those files that match the criteria.

Here’s an example of filtering files with a specific extension using Node.js:

Here’s an example code:

const fs = require('fs');
const path = require('path');

const directoryPath = '/path/to/your/directory';
const desiredExtension = '.txt';

try {
  const files = fs.readdirSync(directoryPath);
  const filteredFiles = files.filter((file) => path.extname(file) === desiredExtension);
  console.log(filteredFiles);
} catch (error) {
  console.error('Error reading directory:', error);
}

In this example, we use the path module to extract the file extension using path.extname.

Then, we filter the list of files to include only those with the extension specified in sampleExtension.

For example:

const fs = require('fs');
const path = require('path');

const directoryPathSample = '/path/to/your/directory';
const sampleExtension = '.txt';

try {
  const files = fs.readdirSync(directoryPathSample);
  const filteredFiles = files.filter((file) => path.extname(file) === sampleExtension);
  console.log(filteredFiles);
} catch (error) {
  console.error('Error reading directory:', error);
}

Excluding Files by Name

If you want to add specific files from the listing, you can apply the same filtering method but with the reverse condition.

Here’s an example of excluding files with a specific name using Node.js:

const fs = require('fs');

const directoryPathSample = '/path/to/your/directory';
const excludedFileNameSample = 'tutorial.txt';

try {
  const files = fs.readdirSync(directoryPathSample);
  const filteredFilesSample = files.filter((file) => file !== excludedFileNameSample);
  console.log(filteredFilesSample);
} catch (error) {
  console.error('Error reading directory:', error);
}

In this case, we filter the list of files to exclude the file named ‘tutorial.txt‘.

Handling Asynchronous File Operations

As file operations may require reading large files or interacting with external APIs, it is necessary to handle these operations asynchronously to prevent blocking the main thread.

JavaScript provides different asynchronous methods for file operations.

Asynchronous File Listing with Node.js

To handle file listing asynchronously in Node.js, you can use the fs.readdir method, which takes a callback function as an argument.

The callback function is executed when the file listing operation is complete.

Here’s an example of listing files asynchronously using Node.js:

const fs = require('fs');

const directoryPath = '/path/to/your/directory';

fs.readdir(directoryPath, (error, files) => {
  if (error) {
    console.error('Error reading directory:', error);
  } else {
    console.log(files);
  }
});

In this example, we pass a callback function to fs.readdir, which receives an error and an array of files.

If an error occurs during the file listing operation, it will take the error parameter. Otherwise, the list of files will be available in the files array.

Asynchronous File Reading on the Client-Side

On the client-side, reading files asynchronously is important to prevent freezing the user interface during file operations.

The FileReader API offers an asynchronous method called readAsText, which reads the contents of a file and triggers a callback function when the operation is complete.

Here’s an example of reading a file asynchronously on the client-side using JavaScript:

<!DOCTYPE html>
<html>

<head>
  <title>Asynchronous File Reading in JavaScript</title>
</head>

<body>
  <input type="file" id="fileInput" multiple>
  <script>
    const fileInput = document.getElementById('fileInput');

    fileInput.addEventListener('change', (event) => {
      const fileListSample = event.target.files;

      for (const file of fileListSample) {
        const fileReader = new FileReader();

        fileReader.addEventListener('load', (event) => {
          const fileContent = event.target.result;
          console.log(fileContent);
        });

        fileReader.readAsText(file);
      }
    });
  </script>
</body>

</html>

In this client-side example, we use the readAsText method of FileReader to read the contents of the selected file.

The load event listener is triggered when the file reading is complete, and we can access the content of the file in the result property of the event.

Organizing File Listings in Tables

Presenting file listings in a tabular format can make it easier for users to view and interact with the information.

Let’s see how you can set up the file listings in tables using HTML and JavaScript.

Creating a File Listing Table

To create a file listing table, we can use HTML to define the table structure and JavaScript to populate the table with file information.

Here’s an example of how to create a file listing table on the client-side:

<!DOCTYPE html>
<html>

<head>
  <title>File Listing Table</title>
</head>

<body>
  <table>
    <thead>
      <tr>
        <th>File Name</th>
        <th>File Size (bytes)</th>
        <th>Last Modified</th>
      </tr>
    </thead>
    <tbody id="fileTableBody"></tbody>
  </table>
  <script>
    const directoryPath = '/path/to/your/directory';
    const fileTableBody = document.getElementById('fileTableBody');

    fetchFileList(directoryPath)
      .then((files) => populateFileTable(files))
      .catch((error) => console.error('Error fetching file list:', error));

    function fetchFileList(path) {
      return new Promise((resolve, reject) => {
        fetch(`/api/listFiles?path=${encodeURIComponent(path)}`)
          .then((response) => response.json())
          .then((data) => resolve(data.files))
          .catch((error) => reject(error));
      });
    }

    function populateFileTable(files) {
      for (const file of files) {
        const row = document.createElement('tr');
        const nameCell = document.createElement('td');
        const sizeCell = document.createElement('td');
        const modifiedCell = document.createElement('td');

        nameCell.textContent = file.name;
        sizeCell.textContent = file.size;
        modifiedCell.textContent = new Date(file.lastModified).toLocaleString();

        row.appendChild(nameCell);
        row.appendChild(sizeCell);
        row.appendChild(modifiedCell);

        fileTableBody.appendChild(row);
      }
    }
  </script>
</body>

</html>

In this example, we make a simple table with three columns: “File Name“, “File Size (bytes)“, and “Last Modified“.

We fetch the file list using the fetchFileList function, which makes a request to the server-side API (e.g., /api/listFiles) to retrieve the file list.

The fetched data is then used to populate the table dynamically.

Working with File Metadata

Apart from the basic file information, it will generally need to access additional metadata associated with files, such as file creation date, file type, or file permissions.

Let’s explore how you can work with file metadata using JavaScript.

Extracting File Metadata with Node.js

In Node.js, you can use the fs.statSync method to achieve file metadata synchronously.

The fs.statSync method returns an object consisting of different properties related to the file.

Here’s an example code of extracting file metadata using Node.js:

const fs = require('fs');

const filePath = '/path/to/your/file';

try {
  const fileStats = fs.statSync(filePath);
  console.log('File Size:', fileStats.size, 'bytes');
  console.log('Created On:', fileStats.birthtime);
  console.log('Last Modified On:', fileStats.mtime);
  console.log('Is Directory:', fileStats.isDirectory());
  console.log('Is File:', fileStats.isFile());
} catch (error) {
  console.error('Error reading file metadata:', error);
}

FAQs

Can I list files in a directory using JavaScript on both the server and client-side?

Yes, you can list files in a directory using JavaScript on both the server and client-side.

On the server-side, you can use Node.js with the fs module to access the file system and list files.

While, on the client-side, you can use the File API provided by HTML5 to interact with files and list them.

How can I filter files based on their extensions?

You can filter files based on their extensions by checking the file name for the proper extension and including only those files that match the criteria.

Is it possible to move a file from one location to another using JavaScript?

Yes, you can move a file from one location to another using JavaScript on the server-side (Node.js).

Conclusion

Managing files in a directory using JavaScript is a necessary skill for web developers.

Whether you are handling file uploads, displaying a list of files, or performing other file operations.

JavaScript provides essential tools to complete these tasks effectively.

Additional Resources

Leave a Comment