简体   繁体   中英

Node.js wait for fs.mkdir() to finish before continuing?

I'm working in Node.js and need to create a new directory. I'm using fs.mkdir() for this.

Howvever, I need this directory to be created or at least check whether the creation was successful or not before moving forward with the next bit of code. How could I get a promise or return value from mkdir() that indicates the success or failure of the code before continuing?

Current code:

    fs.mkdir('./newdirectory', function(err) {
      if (err) {
          console.log("Error Creating Directory: " + err);
       } else{
          console.log("Success Creating Directory")
       }
     })

  //need code here to execute after knowing whether the directory was successfully created or not
  //currently, this code here executes before the 'console.log()' above would

As Christian Fritz mentioned, what you're looking for mkdirSync . It will return undefined in most cases (see: https://nodejs.org/api/fs.html#fs_fs_mkdirsync_path_options ).

All the error validation you need is wrapping it in a try-catch block. It will throw an exception if something goes wrong.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM