Node Asynchronous mkdir with full path

1.8k Views Asked by At

I am currently using shell.js's mkdir -p in my node.js code which is synchronous. The '-p' is used in shell.mkdir to create a directory with a full path, something that fs.mkdir cannot do.

if(fs.existsSync(archivePath + "\\" + site + "\\" + year)){ // check if site folder exists
    console.log(archivePath + "\\" + site + "\\" + year + " exists");
}
else {
    console.log(archivePath + "\\" + site + "\\" + year + " does not exist... creating full path now");
    shell.mkdir('-p' , archivePath + "\\" + site + "\\" + year + "\\" + missionID);
}

If anyone knows of a way to get the asynchronous nature of fs.mkdir, and the recursive nature of shell.mkdir('-p', absolutePath), in one fell swoop please let me know.

2

There are 2 best solutions below

0
On BEST ANSWER

So I figured out that I could just use mkdirp to do a directory with a full path via a promise.
See full documentation here

3
On

You can try using the node module commandir:

mkdir and rmdir that just work

  • The functions are idempotent, so you won't get an error for trying to create a directory that already exists or trying to remove one that doesn't.
  • mkdir creates intermediate directories so you don't have to!
  • mkdir and rmdir will always tell you exactly which directories were created or deleted so your program can clean up after itself if it aborts later in its execution. This is made especially easy by the fact both functions share a consistent API allowing you to pass the output of one as the input to the other!

Install

npm
npm install --save commandir
yarn
yarn add commandir

See the documentation for full usage instructions.

Disclaimer: I'm the author of commandir