0

i have a code in which i am creating a new directory. But the problem is that callback will call earlier while the directory will created. This method is inside the class. How to await until the file will be created and then call callback? I need something async/await, but i don't know how to wrap it. any solutions ?

 createMissingPath(newFilePathname, callback) {
    try {
        let currentIndex = 0;
        while ((currentIndex = newFilePathname.indexOf('/'/*path.sep*/, currentIndex+1))!= -1) {
            let lastPath = newFilePathname.substr(0, currentIndex);
            if(!fs.existsSync(lastPath)) {
                logger.info('Trying to create directory: %s', lastPath);
                fs.mkdir(lastPath);
            }
        }
        callback(null, null);
    }
    catch (exception) {
        logger.error('Caught exception : %s', inspect(exception));
        callback(exception, null);
    }
}
Edward Gizbreht
  • 296
  • 4
  • 19
  • There are a lot of answers to the linked question, but scan down to the one about doing a series of async operations in either parallel or series (you want to do them in series). – T.J. Crowder Jul 25 '17 at 13:39
  • There is a bunch of `mkdir -p`-like modules on the npm. Just an [example](https://www.npmjs.com/package/make-dir) You might don't need to reinvent the wheel. – Yury Tarabanko Jul 25 '17 at 13:42
  • I would advise to use `fs-extra`. it offers allot of this handy features. – Bellian Jul 25 '17 at 13:42
  • no external libraries – Edward Gizbreht Jul 25 '17 at 13:43
  • 2
    I don't think it's a good duplicate. You shouldn't use `fs.exists` before `fs.mkdir`, because it can lead to race condition. A good solution is to check `err.code === 'EEXIST'` when calling `fs.mkdir`. See https://stackoverflow.com/a/21196961/63011 – Paolo Moretti Jul 25 '17 at 13:46

0 Answers0