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 });
JavaScriptAsynchronously
await fs.promises
.mkdir('./path/to/my/directory', { recursive: true });
JavaScriptAssuming 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;
},
'',
);
JavaScriptWith 10.x currently in maintenance mode and at end of life very soon, I’d highly
recommend upgrading Node.js before doing the aforementioned.