Node.js: Multer upload with promise?

痴心易碎 提交于 2019-12-04 10:12:57

This solution worked for me :

Node v8.4.0 is required for this

//app.js
const fs = require('fs');
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const app = express();

app.use(cors({credentials: true, origin: 'http://localhost:4200'}));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

const Uploader = require('./Uploader.js');
const uploader = new Uploader();

app.post('/upload', uploader.startUpload);


//Uploader.js

const util = require("util");
const crypto = require("crypto");
const multer = require('multer');

class Uploader {

    constructor() {
        const storageOptions = multer.diskStorage({
            destination: function(req, file, cb) {
                cb(null, __dirname + '/uploads/')
            },
            filename: function(req, file, cb) {
                crypto.pseudoRandomBytes(16, function(err, raw) {
                    cb(null, raw.toString('hex') + Date.now() + '.' + file.originalname);
                });
            }
        });

        this.upload = multer({ storage: storageOptions });
    }

    async startUpload(req, res) {
        let filename;

        try {
            const upload = util.promisify(this.upload.any());

            await upload(req, res);

            filename = req.files[0].filename;
        } catch (e) {
            //Handle your exception here
        }

        return res.json({fileUploaded: filename});
    }
}

Edit : The library "util" provide you a "promisify" method which will give you the possibility to avoid something called the "callback hell". It converts a callback-based function to a Promise-based one.

This is a small example to understand my code above:

const util = require('util');

function wait(seconds, callback) {
  setTimeout(() => {
    callback();
  }, seconds);
}

function doSomething(callType) {
  console.log('I have done something with ' + callType + ' !');
}

// Default use case
wait(2 * 1000, () => {
  doSomething('callback');
});

const waitPromisified = util.promisify(wait);

// same with promises
waitPromisified(2000).then((response) => {
  doSomething('promise');
}).catch((error) => {
  console.log(error);
});

// same with async/await

(async () => {
  await waitPromisified(2 * 1000);
  doSomething('async/await');
})();

Will print :

I have done something with callback !
I have done something with promise !
I have done something with async/await !
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!