user3569641
user3569641

Reputation: 922

Create folder before upload in express js

How can I create a folder (if the folder does not exist yet) before the image will be uploaded? I always get error ENOENT.

When I try this code:

module.exports = function(router){

    router.post('/result', directory.tmp, uploader.single, function(req,res){ 
           //some data manipulation here
    });
}

//directory.js

module.exports.tmp = function(req, res, next){
        mkdirp('./tmp/' + moment().format('MM-DD-YY') + '/' + moment().format('HH'), function (err) {
            if (err) console.error(err)
            console.log("==================================");
            console.log("tmp folder created");
            console.log("==================================");
        });
        next();
    };

Though I used directory.tmp first so it will create a folder if it is not existing, I think uploader.single is executed first that is why I got that error. After receiving the error, then that's the time my app created the folder. So in other words, the file uploaded was not saved. How to fix this so it will create the folder first, then upload the file. Btw, I am using mkdirp and multer.

Upvotes: 0

Views: 1509

Answers (1)

DevAlien
DevAlien

Reputation: 2476

I would suggest you to do the next(); inside the callback of mkdirp.

Because like you did, why it creates the folder it calls next and goes further and the folder is not yet created. This is why you should wait for folder creation first.

module.exports.tmp = function(req, res, next){
    mkdirp('./tmp/' + moment().format('MM-DD-YY') + '/' + moment().format('HH'), function (err) {
        if (err) console.error(err)
        console.log("==================================");
        console.log("tmp folder created");
        console.log("==================================");
        next();
    });
};

Upvotes: 1

Related Questions