in Software Development #Node.js

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 })

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 += </span><span class="token interpolation"><span class="token interpolation-punctuation punctuation">${</span>directory<span class="token interpolation-punctuation punctuation">}</span></span><span class="token string">/</span><span class="token template-punctuation string">;

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.