Wait for the Google Vision OCR promise in node.js/express and return it
Wait for the Google Vision OCR promise in node.js/express and return it
I am having problems to return a promise from the Google Vision OCR. Here is the sample code from Google:
const vision = require('@google-cloud/vision');
// Creates a client
const client = new vision.ImageAnnotatorClient();
/**
* TODO(developer): Uncomment the following line before running the sample.
*/
// const fileName = 'Local image file, e.g. /path/to/image.png';
// Performs text detection on the local file
client
.textDetection(fileName)
.then(results => {
const detections = results[0].fullTextAnnotation.text;
console.log('Text:');
console.log(detections);
})
.catch(err => {
console.error('ERROR:', err);
});
This will output the full text to the console. If I put the above code into a function and return the variable detections I get only undefined back. I assume the cause of the problem is that a promise is async.
How can I return detections in a route and wait for the promise to resolve so that I can return it via res.send?
This is the function:
function ocrresults(imgpath) {
console.debug("OCR recognition started");
client
.textDetection(imgpath)
.then(results => {
const detections = results[0].fullTextAnnotation.text;
console.log(detections);
return detections;
})
.catch(err => {
var MyError = ('ERROR:' err);
console.error('ERROR:', err);
return MyError;
});
}
This is the route:
app.post('/getmytext', function (req, res) {
var upload = multer({
storage: storage
}).single('userFile')
upload(req, res, function (err) {
res.end(ocrresults(imagepath));
})
})
Thank you.
@FranciscoMateo Done
– thefatman
3 hours ago
1 Answer
1
You can create a separate module:
const vision = require('@google-cloud/vision');
function exportDetections(fileName) {
// Creates a client
const client = new vision.ImageAnnotatorClient();
// Performs text detection on the local file
return client
.textDetection(fileName)
.then(results => {
const detections = results[0].fullTextAnnotation.text;
return detections;
});
}
module.exports = exportDetections;
And in your route import it and use:
app.post('/getmytext', function (req, res) {
var upload = multer({
storage: storage
}).single('userFile')
upload(req, res, function (err) {
exportDetections(imagePath)
.then((detections) => {
res.end(ocrresults(imagepath));
})
})
})
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Please post how you are defining the function.
– Francisco Mateo
3 hours ago