'NodeJS Sync call - PDF Reader

I'm facing a problem to read PDF file synchronously.

To show what I'm trying to do, I create this sample code:

var pdfUtil = require('pdf-to-text');
var pdf_path = "/Users/juliomartins/Desktop/teste2.pdf";

let state = 1;


function pdfToText() {
    pdfUtil.pdfToText(pdf_path, function(err, data) {
        if (err) {
            throw(err);
        }    
        console.log(`Inside...`);
        state = 2;
        return data;
      });
}

while (state !== 3) {
    switch (state) {
        case 1: 
            pdfToText();
            console.log('Call to read pdf...');          
            state = 10;
            continue;
        case 2:
            console.log('Finish...');    
            break;
    };
}        

I expect that the result of this code is:

  1. Print on console: 'Call to read pdf...'
  2. Print on console: 'Inside...'
  3. Print on console 'Finish...'

But the result is:

  1. Print on console: 'Call to read pdf...'
  2. Stuck.

The main goal of this code is wait until PDFtoText finish work to change state on State Machine.

What is wrong in approach ?

Thanks guys!

Julio



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source