1

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.

loretoparisi
  • 15,724
  • 11
  • 102
  • 146

2 Answers2

0

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

fvgs
  • 21,412
  • 9
  • 33
  • 48
  • Thanks for the response, however when I tried it in my code I kept getting an error: C:\Foldername\node_modules\commandir\src\mkdir\index.js:8 async function mkdir (...args) with ^^^^^^^^ under "function". I believe that this is a problem occuring on your end, because after running your sample code I also got an error – Haroun Ansari Nov 30 '17 at 14:09
  • @HarounAnsari Thanks for the feedback! The error occurs because Commandir makes use of async functions which are not supported by older versions of node. I'm glad you were able to solve your problem using mkdirp. If you find you prefer a `mkdir` that returns a promise instead of requiring a callback and are able to upgrade to a recent version of node, I encourage you to give Commandir another try. Best of luck! – fvgs Nov 30 '17 at 18:00
  • Thank you for your help, best of luck on your project. – Haroun Ansari Dec 01 '17 at 14:39
0

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