How to read directories in Node.js

Reading directories in Node.js enables file system exploration, dynamic file processing, and directory structure analysis through the built-in filesystem module methods. As the creator of CoreUI, a widely used open-source UI library, I’ve implemented directory reading in countless Node.js applications for build tools, file processors, and content management systems. From my expertise, the most effective approach is using fs.readdir() with proper error handling and filtering options for specific file types. This method provides efficient directory traversal with comprehensive file information and flexible filtering capabilities.

Use fs.readdir() to list directory contents with options for detailed file information and filtering.

import { readdir, stat } from 'fs/promises'
import { join } from 'path'

// Simple directory reading
async function listFiles(dirPath) {
  try {
    const files = await readdir(dirPath)
    console.log('Files:', files)
    return files
  } catch (error) {
    console.error('Error reading directory:', error.message)
  }
}

// Read with file details
async function listFilesWithDetails(dirPath) {
  try {
    const files = await readdir(dirPath, { withFileTypes: true })

    const fileDetails = files.map(file => ({
      name: file.name,
      isDirectory: file.isDirectory(),
      isFile: file.isFile()
    }))

    return fileDetails
  } catch (error) {
    console.error('Error reading directory:', error.message)
  }
}

// Recursive directory reading
async function readDirRecursive(dirPath) {
  try {
    const items = await readdir(dirPath, { withFileTypes: true })
    const results = []

    for (const item of items) {
      const fullPath = join(dirPath, item.name)

      if (item.isDirectory()) {
        const subItems = await readDirRecursive(fullPath)
        results.push({ name: item.name, type: 'directory', children: subItems })
      } else {
        results.push({ name: item.name, type: 'file', path: fullPath })
      }
    }

    return results
  } catch (error) {
    console.error('Error reading directory recursively:', error.message)
  }
}

// Filter specific file types
async function findJavaScriptFiles(dirPath) {
  try {
    const files = await readdir(dirPath)
    const jsFiles = files.filter(file => file.endsWith('.js') || file.endsWith('.ts'))
    return jsFiles
  } catch (error) {
    console.error('Error finding JS files:', error.message)
  }
}

The fs.readdir() method returns an array of filenames in the specified directory. Use withFileTypes option to get detailed file information including type checking methods. Handle errors with try/catch blocks and use path.join() for cross-platform path construction when building recursive directory readers.

Best Practice Note:

This is the same directory reading approach we use in CoreUI Node.js build tools for processing component files and generating documentation from project structures.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author

Subscribe to our newsletter
Get early information about new products, product updates and blog posts.

Answers by CoreUI Core Team