David Silva Smith David Silva Smith - 1 year ago 253
Node.js Question

How to create full path with node's fs.mkdirSync?

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?

Answer Source

One option is to use shelljs module

npm install shelljs

var shell = require('shelljs');
shell.mkdir('-p', fullPath);

From that page:

Available options:

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download