0

I tryed to make simple script that create a folder if it not exsists. I readed some articles and maked logic like this:

debug("before async");
(async () => {
  if(!fs.existsSync(outputPath)){
    debug("Folder not exsists! path: "+outputPath)
    try{
      return await fs.mkdir(outputPath)
    }catch(err){
      debug(err)
    }
  }
  res.send('<h1>Hello world!</h1>')
})()

I got an error:

(node:27611) [DEP0013] DeprecationWarning: Calling an asynchronous function without callback is deprecated.

Ok. I figured a little and remind that guy from stackoverflow tell me make callback functon as promisify. I tryed to make it:

const mkdir = util.promisify(fs.mkdir);
debug("Before async");
(async () => {
  if(!fs.existsSync(outputPath)){
    debug("Folder not exsists! path: "+outputPath)
    await Promise.all(mkdir(outputPath))
  }
  res.send('<h1>Hello world!</h1>')
})()

But I got other error:

UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 3): TypeError: undefined is not a function

How was I supposed to make all? If you know any guides that can help me to understand about asynchronous functionality - that will be great. Thanks!

btw, both ways folder was created. but with errors...

4 Answers 4

9

Node 11.x.x and later

await fs.promises.mkdir( '/path/mydir' );
Sign up to request clarification or add additional context in comments.

Comments

2

Promise.all is for running an array of promises. In your case, you can just do this:

await mkdir(outputPath)

Depending on your needs, you could potentially do something like this:

await Promise.all([mkdir(path1), mkdir(path2), mkdir(path3)])

I would recommend becoming familiar with callbacks and promises before jumping into async/await.

Comments

1

You cant/dont need to use Promise.all as you only handling one promise anyway, just do

await mkdir(outputPath)

Besides that you really should add some error handling to your code.

Comments

0

Asynchronously checking to see if a folder exists and then creating one if it doesn't. Works from Node.js ^10.20.1.

const fsPromises = require("fs").promises;

async function createDir(dir) {
  try {
    await fsPromises.access(dir, fs.constants.F_OK);
  } catch (e) {
    await fsPromises.mkdir(dir);
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.