Work With Directories in Node.js

Node.js·2 min read·Jan 1, 2025

Read the content of a directory

To list the content of a directory, you can use the fs.readdirSync() static method:

const files = fs.readdirSync(path, { withFileTypes?, recursive? });

Where:

  • files is an array of filenames.
  • path is the path to the target directory.
  • withFileTypes is an optional boolean used to return fs.Dirent objects instead of strings, including the type of each file.
  • recursive is an optional boolean used to recursively list the content of the target directory.

Note: This function is similar to the Unix ls command.

Example

Let's consider this script that generates a visual tree-like structure of a directory:

tree.js
const fs = require('node:fs');const path = require('node:path');

Unlock the program 🚀

Pay once, own it forever.

€79

30-day money-back guarantee

  • 13 modules
  • 113 lessons with full-code examples
  • 29 projects with commented solutions
  • All future lesson and project updates
  • Lifetime access

By submitting this form, you agree to the Terms & Conditions and Privacy Policy.