SQS Receive message using javascript
const AWS = require("aws-sdk");
const sqs = new AWS.SQS({apiVersion: "2012-11-05"});
const qurl = "ADD YOUR SQS URL HERE";
const params = {
"QueueUrl": qurl,
"MaxNumberOfMessages": 1
};
// By using Callback
sqs.receiveMessage(params, (err, data) => {
if (err) {
console.log(err, err.stack);
} else {
if (!Array.isArray(data.Messages) || data.Messages.length === 0) {
console.log("There are no messages available for processing.");
return;
}
const body = JSON.parse(data.Messages[0].Body);
console.log(body);
// process the body however you see fit.
// once the processing of the body is complete, delete the message from the SQS to avoid reprocessing it.
const delParams = {
"QueueUrl": qurl,
"ReceiptHandle": data.Messages[0].ReceiptHandle
};
// delete messages
sqs.deleteMessage(delParams, (err, data) => {
if (err) {
console.log("There was an error", err);
} else {
console.log("Message processed Successfully");
}
});
}
});
// Promise implementation
sqs.receiveMessage(params).promise()
.then(data => {
console.log(data);
// do the processing here
//delete the messages
});
Resources:
- Getting Started with AWS SQS using Javascript- Part 1
- Getting Started with AWS SQS using Javascript- Part 2
- Github Repo for code
I would love to hear what you think about this snippet and if there is anything you would like me to add in future. Drop me a line on @awsmag.
Previous SnippetSQS Send message using javascript