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?
One option is to use shelljs module
npm install shelljs
var shell = require('shelljs'); shell.mkdir('-p', fullPath);
From that page:
p: full path (will create intermediate dirs if necessary)
As others have noted, there’s other more focused modules. But, outside of mkdirp, it has tons of other useful shell operations (like which, grep etc…) and it works on windows and *nix
Edit: comments suggest this doesn’t work on systems that don’t have mkdir cli instances. That is not the case. That’s the point shelljs – create a portable cross platform set of shell like functions. It works on even windows.
Answered By – bryanmac
Answer Checked By – Mary Flores (AngularFixing Volunteer)