Example of using Yandex Message Queue on Node.js
Node.js
Installing
Install the AWS SDK for JavaScript in Node.js by following the instructions
npm install @aws-sdk/client-sqs@3.445.0
Getting started
- Create a service account.
- Assign the editor role to the service account.
- Create a static access key.
Set the environment variables:
export AWS_ACCESS_KEY_ID="<access_key_ID>"
export AWS_SECRET_ACCESS_KEY="<secret_key>"
Example
In this example:
- A connection with Message Queue is established.
- A message queue named
mq_example_nodejs_sdk
is created. - A message with the text
test message
is sent to the queue. - The message is read from the queue and displayed in the terminal.
- The message queue is deleted.
var AWS = require('aws-sdk');
var mq = new AWS.SQS({
'region': 'ru-central1',
'endpoint': 'https://message-queue.api.cloud.yandex.net',
});
async function createQueue() {
params = {
'QueueName': 'mq_example_nodejs_sdk',
}
result = await mq.createQueue(params).promise();
queueUrl = result['QueueUrl'];
console.log('Queue created, URL: ' + queueUrl);
return queueUrl;
}
async function sendMessage(queueUrl) {
params = {
'QueueUrl': queueUrl,
'MessageBody': 'test message',
}
result = await mq.sendMessage(params).promise();
console.log('Message sent, ID: ' + result['MessageId']);
}
async function receiveMessage() {
params = {
'QueueUrl': queueUrl,
'WaitTimeSeconds': 10,
}
result = await mq.receiveMessage(params).promise();
result['Messages'].forEach(async function(msg) {
console.log('Message received')
console.log('ID: ' + msg['MessageId'])
console.log('Body: ' + msg['Body'])
deleteParams = {
'QueueUrl': queueUrl,
'ReceiptHandle': msg['ReceiptHandle'],
}
await mq.deleteMessage(deleteParams).promise()
})
}
async function deleteQueue() {
params = {
'QueueUrl': queueUrl,
}
result = await mq.deleteQueue(params).promise();
console.log('Queue deleted')
}
async function main() {
queueUrl = await createQueue();
await sendMessage(queueUrl);
await receiveMessage(queueUrl);
await deleteQueue(queueUrl);
}
main()