I'm trying to create a full path if it doesn't exist.
The code looks like this:
var fs = require('fs');
if (!fs.existsSync(newDest)) fs.mkdirSync(newDest);
This code works great as long as there is only one subdirectory (a newDest like 'dir1') however when there is a directory path like ('dir1/dir2') it fails with
Error: ENOENT, no such file or directory
I'd like to be able to create the full path with as few lines of code as necessary.
I read there is a recursive option on fs and tried it like this
var fs = require('fs');
if (!fs.existsSync(newDest)) fs.mkdirSync(newDest,'0777', true);
I feel like it should be that simple to recursively create a directory that doesn't exist. Am I missing something or do I need to parse the path and check each directory and create it if it doesn't already exist?
I'm pretty new to Node. Maybe I'm using an old version of FS?
Best Answer
Edit
NodeJS version
10.12.0
has added a native support for bothmkdir
andmkdirSync
to create a directory recursively withrecursive: true
option as the following:And if you prefer
fs Promises API
, you can writeOriginal Answer
Create directories recursively if they do not exist! (Zero dependencies)
Usage
Demo
Try It!
Explanations
EISDIR
for Mac andEPERM
andEACCES
for Windows. Thanks to all the reporting comments by @PediT., @JohnQ, @deed02392, @robyoder and @Almenon.{isRelativeToScript: true}
.path.sep
andpath.resolve()
, not just/
concatenation, to avoid cross-platform issues.fs.mkdirSync
and handling the error withtry/catch
if thrown to handle race conditions: another process may add the file between the calls tofs.existsSync()
andfs.mkdirSync()
and causes an exception.if (!fs.existsSync(curDir) fs.mkdirSync(curDir);
. But this is an anti-pattern that leaves the code vulnerable to race conditions. Thanks to @GershomMaes comment about the directory existence check.