How to create directories in Node.js

Creating directories programmatically is essential for organizing file uploads, generating project structures, and managing application data in Node.js applications. As the creator of CoreUI, a widely used open-source UI library, I’ve implemented directory creation in countless backend services and build tools over 25 years of development. From my expertise, the most reliable approach is using fs.mkdir() with the recursive option, which creates parent directories automatically if they don’t exist. This prevents errors and ensures the complete directory path is created.

Use fs.mkdir() with recursive option to create directories and parent paths.

const fs = require('fs')

fs.mkdir('./uploads/images/thumbnails', { recursive: true }, (err) => {
  if (err) throw err
  console.log('Directory created successfully')
})

Here fs.mkdir() creates the specified directory path, including any missing parent directories thanks to the { recursive: true } option. Without this option, the method would fail if ‘uploads’ or ‘images’ directories don’t exist. The recursive option ensures the entire path is created atomically, making it safe for complex nested structures.

Best Practice Note:

This is the same directory creation approach we use in CoreUI build processes for generating output folders and organizing assets. Always use the recursive option for nested paths, and consider using fs.promises.mkdir() with async/await for cleaner asynchronous code in modern Node.js applications.


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.
What is the difference between typeof and instanceof in JavaScript
What is the difference between typeof and instanceof in JavaScript

How to loop inside React JSX
How to loop inside React JSX

How to Remove the Last Character from a String in JavaScript
How to Remove the Last Character from a String in JavaScript

How to Achieve Perfectly Rounded Corners in CSS
How to Achieve Perfectly Rounded Corners in CSS

Answers by CoreUI Core Team