Search code examples
node.jsamazon-web-servicesaws-lambdaamazon-textract

AWS textract methods in node js are not getting invoked


I want to extract text from image using node js so created a lambda in aws. Please find the below code snippet. Issue is that the textract method detectDocumentText is not getting invoked.

As far as permission I had given s3 full access and textract full access to the lambda. Am I missing anything?

var AWS = require("aws-sdk");
var base64 = require("base-64");
var fs = require("fs");
exports.handler = async (event, context, callback) => {
  // Input for textract can be byte array or S3 object

  AWS.config.region = "us-east-1";
  //AWS.config.update({ region: 'us-east-1' });
  var textract = new AWS.Textract({ apiVersion: "2018-06-27" });
  //var textract = new AWS.Textract();
  console.log(textract);

  var params = {
    Document: {
      /* required */
      //'Bytes': imageBase64
      S3Object: {
        Bucket: "717577",
        Name: "Picture2.png"
      }
    }
  };

  textract.detectDocumentText(params, function(err, data) {
    if (err) {
      console.log(err); // an error occurred
    } else {
      console.log(data); // successful response

      callback(null, data);
    }
  });
};

As well as I don't see any error logs in cloudwatch logs.


Solution

  • The problem is that you have marked your method as async which means that you are returning a promise. In your case you are not returning a promise so for lambda there is no way to complete the execution of the method. You have two choices here

    • Remove async
    • Or more recommended way is to convert your callback style to use promise. aws-sdk support .promise method on all methods so you could leverage that. The code will look like this
    var AWS = require("aws-sdk");
    var base64 = require("base-64");
    var fs = require("fs");
    exports.handler = async (event, context) => {
      // Input for textract can be byte array or S3 object
    
      AWS.config.region = "us-east-1";
      //AWS.config.update({ region: 'us-east-1' });
      var textract = new AWS.Textract({ apiVersion: "2018-06-27" });
      //var textract = new AWS.Textract();
      console.log(textract);
    
      var params = {
        Document: {
          /* required */
          //'Bytes': imageBase64
          S3Object: {
            Bucket: "717577",
            Name: "Picture2.png"
          }
        }
      };
    
      const data = await textract.detectDocumentText(params).promise();
      return data;
    };
    
    

    Hope this helps.