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:
filesis an array of filenames.pathis the path to the target directory.withFileTypesis an optional boolean used to returnfs.Direntobjects instead of strings, including the type of each file.recursiveis an optional boolean used to recursively list the content of the target directory.
Note: This function is similar to the Unix
lscommand.
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.