This topic describes how to use the Node.js AMQP SDK to access Alibaba Cloud IoT Platform and receive messages subscribed.

Development environment

In this example, Node.js 8.0.0 or later is used.

Download the SDK

We recommend that you use the rhea library for the Node.js AMQP SDK. You can visit rhea to download the library and view its instructions.

Add the dependency

Add the following dependency to the package.json file:

"Dependencies": {
    "rhea": "^1.0.12"
 }

Sample code

For information about parameters in the following demo, see AMQP client access instructions.

const container = require('rhea');
const crypto = require('crypto');

//Create Connection
var connection = container.connect({
    'host': '${uid}.iot-amqp.${regionId}.aliyuncs.com',
    'port': 5671,
    'transport':'tls',
    'reconnect':true,
    'idle_time_out':60000,
    'username':'${YourClientId}|authMode=aksign,signMethod=hmacsha1,timestamp=1573489088171,authId=${YourAccessKeyID},consumerGroupId=${YourConsumerGroupId}|',
    'password': hmacSha1('${YourAccessKeySecret}', 'authId=${YourAccessKeyID}&timestamp=1573489088171'),
});

//Create Receiver Link
var receiver = connection.open_receiver();

//handle received message
container.on('message', function (context) {
    var msg = context.message;
    var messageId = msg.message_id;
    var topic = msg.application_properties.topic;
    var content = Buffer.from(msg.body.content).toString();

    //ACK
    context.delivery.accept();
});

//calculate password
function hmacSha1(key, context) {
    return Buffer.from(crypto.createHmac('sha1', key).update(context).digest())
        .toString('base64');
}