Search code examples
javascriptnode.jspdftotext

Use Counter in Loop Functions Async Callback


I have a PDF and wish to extract each page of text to it's own document. So that 1.txt contains all text from the first page, 2.txt contains all the text from the second page, and so on...

However, by the time it has to write the file, the counter i is already at pages, I only end up with the last page saved to a text file.

  let pages = 8
  for (var i = 0; i < pages; i++) {
    var option = {from: i, to: i + 1};
    pdfUtil.pdfToText(toFolder + "document.pdf", option, function(err, data) {
      if (err) throw(err);
      fs.writeFile(toFolder + (option.to) + '.txt', data, (err) => {
        console.log("file saved", option.to)
      })
    });
  }

Why does option.to always equal 9 when it comes time to save?

How can I prevent this?


Solution

  • Wrap you code inside of loop in IIFE like this:

      let pages = 8
      for (var i = 0; i < pages; i++) {
        var option = {from: i, to: i + 1};
        (function(option) {
          pdfUtil.pdfToText(toFolder + "document.pdf", option, function(err, data) {
            if (err) throw(err);
            fs.writeFile(toFolder + (option.to) + '.txt', data, (err) => {
               console.log("file saved", option.to)
            })
          });
        })(option);
      }