0

I'm creating a script which reads data from pdf in node, I'm using pdf_text_extract, and I'm trying to return the data with Bluebird.

Types.js:

var pdf = require('pdf');

var Types = {
    read: function(file, extension) {
        pdf.extract(file, function(error, data) {
            console.log(data);
        });
    }
};

module.exports = Types;

The data is a [Function], this is clearly wrong.

Pdf.js:

var Promise             = require('bluebird');
var pdf_text_extract    = require('pdf-text-extract');

var Pdf = {
    extract: function(file, cb) {
        return new Promise(function(resolve, reject) {
            if (reject) {
                console.log(reject);
            }

            pdf_text_extract(file, function(error, data) {
                if (error) {
                    console.log(error);
                }

                resolve(data);
            });
        });
    }
};

module.exports = Pdf;

I'm trying to access the data in other archive, which is calling the Types.js.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375

1 Answers1

2

No, the data is not a function. The cb function you're passing is completely ignored and never executed, the log you are seeing is from console.log(reject); (as reject is always truthy).

Correct would be

var pdf = {
    extract: function(file) {
        return new Promise(function(resolve, reject) {
            pdf_text_extract(file, function(error, data) {
                if (error) 
                    reject(error);
                else
                    resolve(data);
            });
        });
    }
};
var types = {
    read: function(file, extension) {
        return pdf.extract(file).then(function(data) {
            console.log(data);
        }, function(error) {
            console.log(error);
        });
        // returns a promise that fulfills with undefined once data or error are received
    }
};

Or much simpler

var pdf = {
    extract: Promise.promisify(pdf_text_extract)
};
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • Nice, thanks very much Bergi. But i have a question. I'm calling the types in other file, and i need return the data for this file, this is possible?? –  Aug 24 '15 at 15:53
  • @AmandaFerrari: No, it's not, but you can return the promise for the data. – Bergi Aug 24 '15 at 16:01
  • Bergi, but if i try to return the promise, the output will be something strange like: { _bitField: 0, _fulfillmentHandler0: undefined, _rejectionHandler0: undefined, _progressHandler0: undefined, _promise0: undefined, _receiver0: undefined, _settledValue: undefined } –  Aug 24 '15 at 16:14
  • Yes, that is what a Bluebird promise looks like in the console – Bergi Aug 24 '15 at 16:35