Node.js fs.readdirSync() method explained (with examples)

avatar
Borislav Hadzhiev

Last updated: Apr 5, 2024
5 min

banner

# Table of Contents

  1. Node.js fs.readdirSync() method explained (with examples)
  2. Reading the contents of the current directory with fs.readdirsync()
  3. Reading the contents of a relative path with fs.readdirsync()
  4. Getting the File Types of the files in the directory
  5. Filtering for files with specific extensions
  6. Going 1 or more directories up
  7. Reading the contents of a relative path with __dirname

# Node.js fs.readdirSync() method explained (with examples)

The fs.readdirSync() method is used to read the contents of the specified directory.

The method returns an array containing the file names in the given directory.

The fs.readdirSync method takes the following 2 parameters:

  • path - the path to the directory to read from. It can be of type string, Buffer or URL.
  • options - an optional options object used to specify the encoding and the type of the returned objects.
    • encoding - a string used to specify the character encoding to use for the returned filenames. It defaults to utf8.
    • withFileTypes - if set to true, the returned array will contain fs.Dirent objects.

# Reading the contents of the current directory with fs.readdirsync()

Let's start with an example that uses the fs.readdirsync() method to read the contents of the current directory.

index.js
import fs from 'fs'; import path from 'path'; import {fileURLToPath} from 'url'; const __filename = fileURLToPath(import.meta.url); console.log('file name: ', __filename); const __dirname = path.dirname(__filename); console.log('directory name: ', __dirname); const dirContents = fs.readdirSync(__dirname); console.log(dirContents);

read contents current directory

The code for this article is available on GitHub

The code sample uses the path module to get the directory name of the current module.

We can pass the directory name to the fs.readdirSync() method to get the names of the files in the directory.

The output from the example looks similar to the following:

output
file name: /home/borislav/Desktop/bobbyhadz-rest/bobbyhadz-js/index.js directory name: /home/borislav/Desktop/bobbyhadz-rest/bobbyhadz-js [ '.env', '.git', '.gitignore', '.vscode', 'another-file.js', 'another.js', 'example.json', 'example.mdx', 'example.png', 'example.txt', 'example2', 'index.html', 'index.js', 'javascript.md', 'node_modules', 'output.webp', 'package-lock.json', 'package.json', 'utils.js', 'video.mp4' ]

As shown in the output, the __dirname variable stores the absolute path to the current directory.

# Reading the contents of a relative path with fs.readdirsync()

You can also use the fs.readdirsync() method to read the contents of a directory given a relative path.

Assuming you have the following folder structure.

shell
my_project/ static/ another.js example.png script.js utils.js video.mp4 index.js

You can read the contents of the static directory as follows.

index.js
import fs from 'fs'; const dirContents = fs.readdirSync('./static'); // ๐Ÿ‘‡๏ธ [ 'another.js', 'example.png', 'script.js', 'utils.js', 'video.mp4' ] console.log(dirContents);

readdirsync relative directory

The code for this article is available on GitHub

The code sample assumes that there is a static directory located right next to your index.js file.

The './' prefix is used to specify a relative path (relative to the script, e.g. index.js in the example).

# Getting the File Types of the files in the directory

You can set the withFileTypes property in the options object to true to get fs.Dirent objects instead of strings in the output array.

The objects can be used to get the extensions of the files.

index.js
import fs from 'fs'; const dirContents = fs.readdirSync('./static', { withFileTypes: true, }); console.log(dirContents);

The code sample produces the following output:

output
[ Dirent { name: 'another.js', [Symbol(type)]: 1 }, Dirent { name: 'example.png', [Symbol(type)]: 1 }, Dirent { name: 'script.js', [Symbol(type)]: 1 }, Dirent { name: 'utils.js', [Symbol(type)]: 1 }, Dirent { name: 'video.mp4', [Symbol(type)]: 1 } ]

get file types readdirsync

The code for this article is available on GitHub

Each Dirent object has a name property that points to the name of the file.

# Filtering for files with specific extensions

You can't set an option to only select files with specific extensions, however, you can use the Array.filter() method to filter the array after.

index.js
import fs from 'fs'; import path from 'path'; const dirContents = fs.readdirSync('./static', { withFileTypes: true, }); const onlyJsFiles = dirContents.filter(file => { return path.extname(file.name) === '.js'; }); console.log(onlyJsFiles);

The code sample produces the following output.

output
[ Dirent { name: 'another.js', [Symbol(type)]: 1 }, Dirent { name: 'script.js', [Symbol(type)]: 1 }, Dirent { name: 'utils.js', [Symbol(type)]: 1 } ]

only filter for specific files

We used the Array.filter() method to filter the array of objects to only contain ones with a .js extension.

The function we passed to the Array.filter() method gets called with each element in the array.

The path.extname() method returns the extension of the given path.

index.js
import path from 'path'; console.log(path.extname('index.js')); // ๐Ÿ‘‰๏ธ .js console.log(path.extname('index.html')); // ๐Ÿ‘‰๏ธ .html

On each iteration, we check if the current file has a .js extension and return the result.

The filter() method returns a new array that only contains the elements that meet the condition.

# Going 1 or more directories up

If the directory you are trying to read from is located one or more directories up, you have to use the '../ prefix for every directory you have to go up.

Assume we have the following folder structure.

shell
Desktop/ static/ another.js example.png script.js utils.js video.mp4 my_project/ index.js
The code for this article is available on GitHub

You can read the contents of the static/ directory from your index.js file by specifying a path of '../static'.

index.js
import fs from 'fs'; const dirContents = fs.readdirSync('../static'); // ๐Ÿ‘‡๏ธ [ 'another.js', 'example.png', 'script.js', 'utils.js', 'video.mp4' ] console.log(dirContents);

read from one or more directories up

The '../' prefix is used to specify a relative path that goes one directory up.

If you need to go 2 directories up, you would use a prefix of '../../'.

# Reading the contents of a relative path with __dirname

Sometimes reading the contents of a relative directory causes issues on Windows.

If you specify a path prefixed with './', e.g. './static' and aren't able to find it, its best to use the path.resolve() method to construct the path.

Assuming you have the following folder structure.

shell
my_project/ static/ another.js example.png script.js utils.js video.mp4 index.js

This is how we'd construct the path to the static/ directory using path.resolve().

index.js
import fs from 'fs'; import path from 'path'; import {fileURLToPath} from 'url'; const __filename = fileURLToPath(import.meta.url); console.log('file name: ', __filename); const __dirname = path.dirname(__filename); console.log('directory name: ', __dirname); const dirContents = fs.readdirSync( path.resolve(__dirname, './static'), ); console.log(dirContents);
The code for this article is available on GitHub

The code sample produces the following output:

output
file name: /home/borislav/Desktop/bobbyhadz-rest/bobbyhadz-js/index.js directory name: /home/borislav/Desktop/bobbyhadz-rest/bobbyhadz-js [ 'another.js', 'example.png', 'script.js', 'utils.js', 'video.mp4' ]

construct path to relative directory

The path.resolve() method takes multiple paths as parameters and resolves the sequence of paths into an absolute path.

index.js
import fs from 'fs'; import path from 'path'; import {fileURLToPath} from 'url'; const __filename = fileURLToPath(import.meta.url); console.log('file name: ', __filename); const __dirname = path.dirname(__filename); console.log('directory name: ', __dirname); // ๐Ÿ‘‡๏ธ /home/borislav/Desktop/bobbyhadz-rest/bobbyhadz-js/static console.log(path.resolve(__dirname, './static'));
The code for this article is available on GitHub

The method is useful when you encounter operating system-specific issues.

For example, the path separator on Windows is a backslash \, whereas the path separator on macOS and Linux is a forward slash /.

This sometimes causes issues when writing out paths manually and running your code on different platforms.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev