Node > 10.12.0
fs.mkdir now accepts a { recursive: true } option like so:
// Creates /tmp/a/apple, regardless of whether `/tmp` and /tmp/a exist.
fs.mkdir('/tmp/a/apple', { recursive: true }, (err) => {
if (err) throw err;
});
or with a promise:
fs.promises.mkdir('/tmp/a/apple', { recursive: true }).catch(console.error);
Notes,
-
In many case you would use
fs.mkdirSyncrather thanfs.mkdir -
It is harmless / has no effect to include a trailing slash.
-
mkdirSync/mkdir no nothing harmlessly if the directory already exists, there’s no need to check for existence.
Node <= 10.11.0
You can solve this with a package like mkdirp or fs-extra. If you don’t want to install a package, please see Tiago Peres França’s answer below.