Search code examples
javascriptnode.jsamazon-sqs

node.js using SQS need functional example


var params = {
    QueueUrl: sqsEndPoint + compInfoQueName,
    AttributeNames: [All],
    MaxNumberOfMessages: '5',
    MessageAttributeNames: [],
    ReceiveRequestAttemptId: "",
    VisibilityTimeout: '15',
    WaitTimeSeconds: '10'
};

sqs.receiveMessage(params, function (err, data) {
    if (err) console.log(err, err.stack);
    else return data;
});

Got this from AWS website

I have all the params set and can get a response on an html page using:

https://sqs.us-west-2.amazonaws.com/ACCOUNT/QUEUENAME";

But I am wanting to integrate this into a node.js project

I am new to javascript, in java I would just import the AWS object and call a method in a function ie.

function... {json response = sqs.receive... }

How do I use the code at the top in JS?

How do I set a string object to a result from receive with the code example?

I just want to set a field in an html page to the received sqs message

textarea.value = myMessageFromAWS


Solution

  • Since you come from Java the callbacks are not very intuitive.

    I'd recommend you to use the async/await approach so the code looks more linear, like this:

    async function main () {
      var params = {
        QueueUrl: sqsEndPoint + compInfoQueName,
        AttributeNames: [All],
        MaxNumberOfMessages: '5',
        MessageAttributeNames: [],
        ReceiveRequestAttemptId: "",
        VisibilityTimeout: '15',
        WaitTimeSeconds: '10'
      };
    
      try {
        // this will be your data received from sqs
        const data = await sqs.receiveMessage(params).promise()
        // prints to stdout
        console.log(data)
    
      } catch(err) {
        // prints to stderr
        console.error(err, err.stack);
      };
    }
    
    // Because this is not Java you have to call this function explicitly
    main()