Problem with read file pdf from URL nodeJS

Viewed 137

I'm using pdf.js-extract to read data pdf file from URL. This is my code and it runs well:

const fs = require('fs');
const PDFExtract = require('pdf.js-extract').PDFExtract;
const pdfExtract = new PDFExtract();
const https = require('https');

const url = 'https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf'

const readData = async (url) => {
    https.get(url, async function (response) {
        const file = fs.createWriteStream('./dummy.pdf');
        response.pipe(file);
        file.on("finish", () => {
            pdfExtract.extract('./dummy.pdf', {})
            .then(async function(data) {
                console.log(data)
            });
            file.close();
            fs.unlinkSync('./dummy.pdf')
        });
    });
}

readData(url)

But I have 2 problem about this code.

  1. The first is that how can I deal with if the url changes from https to http, I try node-fetch but it's seem not work as I expected.
  2. The second one is that the code take too long to handle if the pdf file is large, about 5 seconds for 2 Mbs. I wonder if there is a faster way like reading the file from the buffer or something like that without having to save it as a temporary file

Thanks for your attention

0 Answers
Related