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?

22 Answers
22

Leave a Comment