,

Sending and Receiving SQS Messages with AWS Lambda and NodeJS šŸš€

Posted by

AWS Lambda Send and Receive SQS Messages – Using NodeJS

AWS Lambda Send and Receive SQS Messages – Using NodeJS šŸš€

AWS Lambda is a serverless computing service provided by Amazon Web Services (AWS) that allows you to run code without managing servers. One use case for AWS Lambda is to send and receive messages from Amazon Simple Queue Service (SQS) using NodeJS.

Sending Messages to SQS

To send messages to an SQS queue using AWS Lambda and NodeJS, you can use the AWS SDK for JavaScript. First, make sure to create an SQS queue in the AWS Console and note its URL. Then, you can write a Lambda function that uses the SDK to send a message to the queue:


const AWS = require('aws-sdk');
const sqs = new AWS.SQS();

exports.handler = async (event) => {
const params = {
MessageBody: 'Hello from AWS Lambda!',
QueueUrl: 'YOUR_QUEUE_URL'
};

await sqs.sendMessage(params).promise();

return {
statusCode: 200,
body: 'Message sent successfully!'
};
};

Receiving Messages from SQS

To receive messages from an SQS queue using AWS Lambda and NodeJS, you can use the SDK to poll for messages and process them. Here’s an example Lambda function that receives messages from the queue:


exports.handler = async (event) => {
const params = {
QueueUrl: 'YOUR_QUEUE_URL'
};

const data = await sqs.receiveMessage(params).promise();

if (data.Messages) {
for (const message of data.Messages) {
// Process the message here
console.log(message.Body);

// Delete the message from the queue
await sqs.deleteMessage({
QueueUrl: 'YOUR_QUEUE_URL',
ReceiptHandle: message.ReceiptHandle
}).promise();
}
}

return {
statusCode: 200,
body: 'Messages processed successfully!'
};
};

Using AWS Lambda to send and receive messages from SQS is a powerful way to build scalable and event-driven applications in the cloud. With NodeJS and the AWS SDK, you can easily integrate these services and automate message processing tasks.