List files in a directory using nodejs
Tags: node, javascript
Published: 2023-09-24 09:27:36

When working with Node.js, it's common to need to read the contents of a directory, which may include both files and directories. In this article, we'll explore different methods to accomplish this task, and we'll also discuss the benefits of each approach.

## 1: Reading All Files and Folders in a directory


In this method, we'll read all files and folders in a directory without using the “path” package. We'll rely solely on the built-in “fs” (file system) module.

```javascript
const fs = require('fs');

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

// Use fs.readdirSync to read the contents of the directory synchronously
const fileList = fs.readdirSync(directoryPath);

console.log('Files and folders in the directory:', fileList);
```
###Output:
![List all files and folders](http://res.cloudinary.com/dkxqdjgdl/image/upload/v1695542494/list-files-and-folders.png.png)
Benefits of this Approach:

- Simplicity: This method is straightforward and does not require additional dependencies. It's a quick way to list the contents of a directory.

- Synchronous: fs.readdirSync is a synchronous operation, which means it will block the Node.js event loop until the directory reading is complete. This can be beneficial in some scenarios when you want to ensure that the directory reading is finished before proceeding with other tasks.

## 2: Reading Files and Folders using fs.readdir (Asynchronous)

In this method, we'll read all files and folders in a directory using the fs.readdir method, which is asynchronous.

```javascript
const fs = require('fs');

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

// Use fs.readdir to read the contents of the directory asynchronously
fs.readdir(directoryPath, (err, files) => {
  if (err) {
    console.error('Error reading directory:', err);
    return;
  }

  console.log('Files and folders in the directory:', files);
});
```

#### Benefits of this Approach:

Non-blocking: This method is non-blocking, which means it won't pause the Node.js event loop while reading the directory. This is advantageous for applications that need to remain responsive.

Error Handling: It provides error handling through the callback function, making it suitable for scenarios where error handling is crucial.

## 3: Reading File Contents using fs.readFileSync

Now, let's explore how to read the contents of a file from the list of files we obtained using one of the previous methods. We'll use fs.readFileSync for this purpose.

```javascript
const fs = require('fs');
const directoryPath = '/path/to/your/directory';

// Assuming you have a fileList obtained from one of the previous methods
fileList.forEach((file) => {
  const filePath = `${directoryPath}/${file}`;

  try {
    const fileContent = fs.readFileSync(filePath, 'utf-8');
    console.log(`Contents of ${file}:`, fileContent);
  } catch (err) {
    console.error(`Error reading ${file}:`, err);
  }
});
```

###Benefits of this Approach:

- Synchronous Reading: fs.readFileSync reads file contents synchronously, which means it will block the event loop while reading the file. Use this method when you want to ensure that the file contents are available immediately.

- Error Handling: It provides error handling through try-catch, making it suitable for scenarios where you need precise control over errors.

##4: Reading Only Files in a Directory
In this method, we'll specifically read and list only the files in a directory, excluding subdirectories.

Asynchronous Approach (Using fs.readdir):

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

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

// Use fs.readdir to read the contents of the directory asynchronously
fs.readdir(directoryPath, (err, items) => {
  if (err) {
    console.error('Error reading directory:', err);
    return;
  }

  // Use async forEach to filter and log only files
  items.forEach((item) => {
    const itemPath = path.join(directoryPath, item);
    fs.stat(itemPath, (statErr, stats) => {
      if (statErr) {
        console.error(`Error reading ${item}:`, statErr);
        return;
      }

      if (stats.isFile()) {
        console.log('File:', item);
      }
    });
  });
});
```

####Benefits of the Asynchronous Approach:

Non-blocking: This method is non-blocking, which is suitable for applications that need to remain responsive while reading files in the directory.

Granular Control: It allows for granular control over each file's properties (e.g., checking if it's a file or a directory) through fs.stat.

Synchronous Approach (Using fs.readdirSync):

```javascript

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

const directoryPath = '/path/to/folder';

// Use fs.readdirSync to read the contents of the directory synchronously
const filesAndFolders = fs.readdirSync(directoryPath);

// Use filter function with path and fs package to filter only files
const files = filesAndFolders.filter((item) => {
  const itemPath = path.join(directoryPath, item);
  const stats = fs.statSync(itemPath);
  return stats.isFile()
})

console.log("Files found in folder: ", files)
```
###Output:
![list only files](http://res.cloudinary.com/dkxqdjgdl/image/upload/v1695542586/list-only-files.png.png)
Benefits of the Synchronous Approach:

- Simplicity: This method is straightforward and does not require nested callbacks or promises. It's a quick way to list only the files in a directory.

- Synchronous Reading: It reads file properties and lists files synchronously, which may be beneficial in cases where you need to ensure that file listing is complete before continuing with other tasks.

### Conclusion
In this comprehensive article, we've covered multiple methods for reading files and folders in a directory using [Node.js](https://milddev.com/tag/nodejs). Each method offers its advantages, ranging from simplicity and blocking behavior to non-blocking asynchronous operations and granular control over file properties. By understanding these methods, you can efficiently work with directories and files in Node.js, making your file management tasks more manageable and reliable.

The article [list all files in a directory using nodejs](https://milddev.com/list-files-in-a-directory-using-nodejs) was originally published on [milddev](https://milddev.com).