Monday 13 March 2017

Promisify an upload with multer

I have some troubles using multer and promises (bluebird). I try to upload a pdf file in a folder then extract the text inside this pdf with the plugin (textract)

Both of the functions I created works, but I have some trouble in the execution and the promisification of the upload function. here's my code :

pdf-rest.js :

var bodyParser = require('body-parser');
var request = require('request');
var jsonParser = bodyParser.json();
var fs = require('fs');
var Promise = require('bluebird');
var multer  = require('multer');
var textract = require('textract');

module.exports = function(app) {

var destination = "uploads";
var filename = "" + Date.now() + ".pdf";
var filePath = "C:\\wamp64\\www\\ebook-stage\\backend\\rest\\uploads\\" + filename;
var storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, destination);
    },
    filename: function (req, file, cb) {
        cb(null, filename);
    }
});
        app.post('/rest/create_pdf', function (req, res) {

            var upload = multer({storage: storage}).single('file');

            function uploadFile() {
                var uploadFilePromise = new Promise(function (resolve, reject) {
                    upload(req, res, function (err) {
                        if (err) {
                            reject(err);
                            res.end('error uploading file')
                        }
                        else {
                            res.end('file uploaded');
                            console.log('fileupload')
                        }
                    });
                    resolve(upload);
                });
                console.log(uploadFilePromise);
                return uploadFilePromise;
            }

            function textractPdf(path) {
                textract.fromFileWithPath(path, function (error, text) {
                    console.log('textract');
                    if (text) {
                        console.log(text);
                        return text;
                    }

                    else {
                        console.log(error);
                        return error;
                    }
                });
            }

            uploadFile().then(textractPdf(filePath));

            });

server.js :

var express = require('express');

var app = express();

require('./pdf-rest.js')(app);

app.listen(8080);

I use a button to execute this script in a HTML page, the upload of the pdf in the folder work the first time I click on the button but the textract doesn't.

I know I do something wrong, the execution of the function textractPdf(Path) is done first. I think I didn't promisify correctly my upload function.



via Florian GĂ©rard

No comments:

Post a Comment