Last updated: Apr 5, 2024
Reading timeยท5 min
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:
options
object used to specify the encoding and
the type of the returned objects.utf8
.true
, the returned array will contain
fs.Dirent
objects.fs.readdirsync()
Let's start with an example that uses the fs.readdirsync()
method to read the
contents of the current directory.
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);
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:
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.
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.
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.
import fs from 'fs'; const dirContents = fs.readdirSync('./static'); // ๐๏ธ [ 'another.js', 'example.png', 'script.js', 'utils.js', 'video.mp4' ] console.log(dirContents);
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).
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.
import fs from 'fs'; const dirContents = fs.readdirSync('./static', { withFileTypes: true, }); console.log(dirContents);
The code sample produces the following 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 } ]
Each Dirent
object has a name
property that points to the name of the file.
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.
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.
[ Dirent { name: 'another.js', [Symbol(type)]: 1 }, Dirent { name: 'script.js', [Symbol(type)]: 1 }, Dirent { name: 'utils.js', [Symbol(type)]: 1 } ]
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.
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.
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.
Desktop/ static/ another.js example.png script.js utils.js video.mp4 my_project/ index.js
You can read the contents of the static/
directory from your index.js
file
by specifying a path of '../static'
.
import fs from 'fs'; const dirContents = fs.readdirSync('../static'); // ๐๏ธ [ 'another.js', 'example.png', 'script.js', 'utils.js', 'video.mp4' ] console.log(dirContents);
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 '../../'
.
__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.
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()
.
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 sample produces the following 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' ]
The path.resolve() method takes multiple paths as parameters and resolves the sequence of paths into an absolute path.
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 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.
You can learn more about the related topics by checking out the following tutorials: