Recursively create directories with Node.js

Recently, while working on a new project, I needed to create a series of nested
directories. From the command-line, it’s easy enough, just pass -p to mkdir
and it will create all of the parent directories automatically.

With modern versions of Node.js, specifically 10 and above, you can achieve the same functionality with fs:

Synchronously

fs.mkdirSync('./path/to/my/directory', { recursive: true });
JavaScript

Asynchronously

await fs.promises
  .mkdir('./path/to/my/directory', { recursive: true });
JavaScript

Assuming you’re on an older version of Node.js and are reluctant to upgrade to
10+, you’ll have to do things a bit more manually.

The gist is, you’ll need to break the path apart and loop through each part of it, creating the non-existent parent directories along the way. That looks something like this:

const path = './path/to/my/directory';

path.split('/').reduce(
  (directories, directory) => {
    directories += `${directory}/`;

    if (!fs.existsSync(directories)) {
      fs.mkdirSync(directories);
    }

    return directories;
  },
  '',
);
JavaScript

With 10.x currently in maintenance mode and at end of life very soon, I’d highly
recommend upgrading Node.js before doing the aforementioned.

Josh Sherman - The Man, The Myth, The Avatar

About Josh

Husband. Father. Pug dad. Musician. Founder of Holiday API, Head of Engineering and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.


If you found this article helpful, please consider buying me a coffee.