Node.js: Multer upload with promise?

Viewed 14494

I have this express route with multer file-upload. When the upload is complete, I would like to encode the image to base64 and send with response.

However when I do it like this, the code tries to execute the base64 encoding before the file is created to the folder.

Edit: Added storage & upload functions

const storage = multer.diskStorage({
    destination: (req, file, callback) => {
        if (!fs.existsSync('./uploads')) {
            fs.mkdirSync('./uploads');
        }
        let path = './uploads';
        callback(null, path);
    },
    filename(req, file, cb) {
        let fileExt = file.originalname.substring(file.originalname.lastIndexOf('.')).toLowerCase();
        if (!imageFilter(fileExt)) {
            return false;
        } else {
            cb(null, file.originalname);
        }
    },
    onError: function (err, next) {
        console.log('error', err);
        next(err);
    },
});

const upload = multer({
    storage,
    limits: {
        fileSize: 1000 * 1000 * 2 // 2 MB
    }
}).single('file');

router.post('/upload', function (req, res) {
    var directory = 'uploads';
    fs.readdir(directory, (err, files) => {
        if (err) throw err;
        for (var file of files) {
            fs.unlink(path.join(directory, file), err => {
                if (err) throw err;
            });
        }
    });
    upload(req, res, function (err) {
        if (err) {
            return res.status(404).json({
                success: false,
                message: 'File is too large. (Max 2MB)'
            });
        }

        var file = req.file;
        var base64str = base64_encode('./uploads/' + file.originalname);

        return res.status(200).json({
            success: true,
            url: 'http://' + ip.address() + ':' + constants.PORT + '/api/uploads/' + file.originalname,
            image: 'data:image/png;base64,' + base64str
        });
    });
});

What would be the smartest way to achieve the right order of operations. Possibly promises or async/await?

1 Answers
Related