How to create directories in Node.js

Creating directories in Node.js enables dynamic folder structure generation, build automation, and file organization through the built-in filesystem module methods. As the creator of CoreUI, a widely used open-source UI library, I’ve implemented directory creation in countless Node.js applications for build systems, project scaffolding, and automated file organization. From my expertise, the most effective approach is using fs.mkdir() with recursive options and proper error handling for nested directory structures. This method provides reliable directory creation with support for complex folder hierarchies and permission management.

Use fs.mkdir() with recursive option to create directories and nested folder structures safely.

import { mkdir, access } from 'fs/promises'
import { constants } from 'fs'

// Simple directory creation
async function createDirectory(dirPath) {
  try {
    await mkdir(dirPath)
    console.log(`Directory ${dirPath} created successfully`)
  } catch (error) {
    if (error.code === 'EEXIST') {
      console.log('Directory already exists')
    } else {
      console.error('Error creating directory:', error.message)
    }
  }
}

// Create nested directories recursively
async function createNestedDirectories(dirPath) {
  try {
    await mkdir(dirPath, { recursive: true })
    console.log(`Directory structure ${dirPath} created successfully`)
  } catch (error) {
    console.error('Error creating nested directories:', error.message)
  }
}

// Create directory with permissions
async function createDirectoryWithPermissions(dirPath, mode = 0o755) {
  try {
    await mkdir(dirPath, { recursive: true, mode })
    console.log(`Directory ${dirPath} created with permissions ${mode.toString(8)}`)
  } catch (error) {
    console.error('Error creating directory with permissions:', error.message)
  }
}

// Safe directory creation (check if exists first)
async function createDirectorySafe(dirPath) {
  try {
    await access(dirPath, constants.F_OK)
    console.log('Directory already exists')
  } catch {
    try {
      await mkdir(dirPath, { recursive: true })
      console.log(`Directory ${dirPath} created successfully`)
    } catch (error) {
      console.error('Error creating directory:', error.message)
    }
  }
}

// Create multiple directories
async function createMultipleDirectories(dirPaths) {
  const results = await Promise.allSettled(
    dirPaths.map(path => mkdir(path, { recursive: true }))
  )

  results.forEach((result, index) => {
    if (result.status === 'fulfilled') {
      console.log(`${dirPaths[index]} created successfully`)
    } else {
      console.error(`Failed to create ${dirPaths[index]}:`, result.reason.message)
    }
  })
}

The fs.mkdir() method creates directories with optional recursive flag for nested structures. Use the recursive option to create parent directories automatically. Handle EEXIST errors gracefully when directories already exist. Set permissions with the mode option for Unix-like systems.

Best Practice Note:

This is the same directory creation approach we use in CoreUI Node.js build tools for generating component structures and organizing build artifacts in automated workflows.


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