Recursively create directories with Node.js

Josh Sherman
1 min read
Software Development 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 })

Asynchronously

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

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;
  },
  '',
);

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.

Join the Conversation

Good stuff? Want more?

Weekly emails about technology, development, and sometimes sauerkraut.

100% Fresh, Grade A Content, Never Spam.

Related Articles