1

I want to receive an image from a client, convert it into text and then delete the image once it's converted. I'm using the following code:

app.post('/upload', (req,res)=>{
    const myFile = req.files.file;
    myFile.mv(`D:/web_projects/react-express-mongodb-template/server/pictures/${myFile.name}`)
    
    let img = `D:/web_projects/react-express-mongodb-template/server/pictures/${myFile.name}`
    convert(img);
    remove(img)
    
})
app.listen(5000, () => {
    console.log('server is running at port 5000');
})
async function convert(img){
  const worker = createWorker();
    
  console.log(worker)
  await worker.load();
  await worker.loadLanguage('eng');
  await worker.initialize('eng');
  const { data: { text } } = await worker.recognize(img);
  console.log(text);
  await worker.terminate();
    
}
async function remove(path){
  try {
    fs.unlink(path)
  } catch(err) {
    console.error(err)
  }
}

So in the post method I call the convert function and then remove but remove gets executed first and so convert function results in error. Is there a way to handle this issue?

4
  • What is createWorker? Commented Mar 8, 2021 at 15:24
  • it's needed to convert images to text Commented Mar 8, 2021 at 18:38
  • Yes, but what is its definition? Are you sure those worker methods return promises? Commented Mar 8, 2021 at 18:39
  • Tbh I don't know the definition but I'm sure it returns promises as I found this code on official github page of tesseract.js Commented Mar 8, 2021 at 18:44

1 Answer 1

1

As convert is an async function, and thus returns a promise, replace:

convert(img);
remove(img)

With:

convert(img).then(() => remove(img));

However, this assumes that all awaited worker method calls in convert return promises. If this is not the case, and they run asynchronous code, then actually convert will not properly await those, and you should first promisify them.

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

Comments

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.