# How to list all files in a directory with Node.js

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published Apr 11, 2020, updated Aug 27, 2022. Topics: Node.js.
Canonical URL: https://attacomsian.com/blog/nodejs-list-directory-files

> A quick guide to learn how to list all files available in a directory using Node.js.

You can use the `f.readdir()` method to list all files available in a directory in Node.js. This method asynchronously reads the contents of the given directory and returns an array of the file names excluding `.` and `..`.

Here is an example that reads all files available in a directory and prints their names on the console:

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

// directory path
const dir = './node_modules/'

// list all files in the directory
fs.readdir(dir, (err, files) => {
  if (err) {
    throw err
  }

  // files object contains all files names
  // log them on console
  files.forEach(file => {
    console.log(file)
  })
})
```

The `fs.readdir()` method will throw an error if the given directory doesn't exist.

Alternatively, you can use the `readdirSync()` method that works synchronously and returns an array of the names of the files:

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

// directory path
const dir = './node_modules/'

// list all files in the directory
try {
  const files = fs.readdirSync(dir)

  // files object contains all files names
  // log them on console
  files.forEach(file => {
    console.log(file)
  })
} catch (err) {
  console.log(err)
}
```

You can also use the promise-based `fsPromises.readdir()` method to read the contents of a directory:

```javascript
const fsPromises = require('fs/promises')

const listFilesAsync = async () => {
  try {
    // directory path
    const dir = './node_modules/'

    const files = await fsPromises.readdir(dir)

    // files object contains all files names
    // log them on console
    files.forEach(file => {
      console.log(file)
    })
  } catch (err) {
    console.error(err)
  }
}

listFilesAsync()
```

Read [this guide](https://attacomsian.com/blog/reading-writing-files-nodejs) to learn more about reading and writing files in a Node.js application.
