Bootstrap FreeKB - Amazon Web Services (AWS) - Get Simple Queue Service (SQS) Messages using Node.js
Amazon Web Services (AWS) - Get Simple Queue Service (SQS) Messages using Node.js

Updated:   |  Amazon Web Services (AWS) articles

This assumes you are familiar with the basic configurations needed to connect to Amazon Web Services (AWS) using NodeJS. If not, check out my article Getting Started with NodeJS aws-sdk.

The @aws-sdk/client-sqs package is used to interact with AWS Simple Queue Service (SQS) in NodeJS. The npm list command can be used to determine if you have the @aws-sdk/client-sqs package installed. If not, the npm install command can be used to install the package. Once installed, your package.json should include the @aws-sdk/client-sqs package.

{
  "dependencies": {
    "@aws-sdk/client-sqs": "^3.693.0"
  }
}

 

This assumes you are already familiar with how to list your AWS Simple Queue Service (SQS) Queues using CommonJS or ES Module. Here is an example of how you could receive 1 message from the queue.

import { SQSClient, ListQueuesCommand, ReceiveMessageCommand  } from "@aws-sdk/client-sqs";
const client = new SQSClient({ region: "us-east-1" });
async function getQueueURL() {
  const params = {
    QueueNamePrefix: "my-first-queue.fifo"
  };
  const command = new ListQueuesCommand(params);
  return await client.send(command);
}
async function receiveMessages(queue_url) {
  const params = {
    QueueUrl: queue_url,
    MaxNumberOfMessages: 1
  }
  const command = new ReceiveMessageCommand(params);
  return await client.send(command);
}
getQueueURL()
  .then(
    response => {
        //response is really only needed for testing/debugging purposes, to see the full response
        //console.log(response)
      if (response.QueueUrls.length != 1) {
        console.error(`response.QueueUrls.length does NOT equal 1`);
        process.exit(1)
      } else {
        var queue_url = response.QueueUrls.toString()
        console.log(`queue URL => ${queue_url}`);
        receiveMessages(queue_url)
          .then(
            response => {
              console.log(response)
            }
          )
          .catch(
            err => {
              console.error(err)
              process.exit(1)
            }
          )
      }
    }
  )
  .catch(
    err => {
      console.error(err)
      process.exit(1)
    }
  )

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 543420 in the box below so that we can be sure you are a human.