Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to list the files in a folder in Node.js

Short answer

readdir() returns the names of everything in the folder:

import { mkdir, readdir, writeFile } from 'node:fs/promises';
 
await mkdir('photos/2025', { recursive: true });
await writeFile('photos/a.jpg', '');
await writeFile('photos/b.png', '');
await writeFile('photos/notes.txt', '');
 
console.log((await readdir('photos')).sort());

Output:

[ '2025', 'a.jpg', 'b.png', 'notes.txt' ]

Files and folders separately

With withFileTypes: true each entry can tell whether it is a file or a folder:

import { mkdir, readdir, writeFile } from 'node:fs/promises';
 
await mkdir('project/src', { recursive: true });
await writeFile('project/README.md', '');
 
const entries = await readdir('project', { withFileTypes: true });
for (const entry of entries) {
  console.log(entry.name, entry.isDirectory() ? 'folder' : 'file');
}

Output:

README.md file
src folder

By extension

Filter the names with extname() from node:path:

import { mkdir, readdir, writeFile } from 'node:fs/promises';
import { extname } from 'node:path';
 
await mkdir('images', { recursive: true });
for (const name of ['cat.jpg', 'dog.JPG', 'list.txt']) await writeFile(`images/${name}`, '');
 
const images = (await readdir('images')).filter((name) => extname(name).toLowerCase() === '.jpg');
console.log(images.sort().join(', '));

Output:

cat.jpg, dog.JPG

With subfolders

The recursive option also lists the content of all subfolders:

import { mkdir, readdir, writeFile } from 'node:fs/promises';
 
await mkdir('docs/guides', { recursive: true });
await writeFile('docs/index.md', '');
await writeFile('docs/guides/start.md', '');
 
const all = await readdir('docs', { recursive: true });
console.log(all.map((name) => name.replaceAll('\\', '/')).sort().join(', '));

Output:

guides, guides/start.md, index.md

Common mistake

readdir() returns only names, not full paths. To open a file, join the folder and the name with join():

import { mkdir, readdir, readFile, writeFile } from 'node:fs/promises';
import { join } from 'node:path';
 
await mkdir('data', { recursive: true });
await writeFile('data/a.txt', 'content of a');
 
for (const name of await readdir('data')) {
  console.log(await readFile(join('data', name), 'utf8'));
}

Output:

content of a

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.