0

I'm using the following javascript solution to get the number of pages of a file :

const reader = new FileReader()
reader.readAsBinaryString(file)
reader.onloadend = function () {
 const count = reader.result.match(/\/Type[\s]*\/Page[^s]/g).length
 console.log('Number of Pages:', count)
}

The number of pages is correct in the console but I don't know how to extract that number from the scope of the reader so I can use it elsewhere. I've read How to return the response from an asynchronous call but I don't understand how to implement it for my case

1
  • you'll need a callback, or a Promise (which is just a fancy callback mechanism) to access that data. The code you've shown isn't enough to help much more than that Commented Aug 6, 2021 at 8:49

1 Answer 1

1

Wrap it in a promise and resolve the value you want:

function getPageNumber() {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsBinaryString(file)
    reader.onloadend = function () {
       const count = reader.result.match(/\/Type[\s]*\/Page[^s]/g).length
       console.log('Number of Pages:', count);
      resolve(count);
    }
  }
}

getPageNumber().then(count => {
  // here, now you have count
});

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks it works fine when I print count inside the .then but I can not seem to extract that value outside of this
You need to read up on how async functions work and get a good feel for it. The patterns of thought and design you're currently using won't work, you've gotta figure the async nature of JS out.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.