In AWS SDK v3, for subscribing to an MQTT topic, you’d typically use the AWS IoT Device SDK rather than the AWS SDK for JavaScript v3. The AWS SDK for JavaScript (v3) is primarily designed for managing AWS services, such as publishing messages via the IoT Data Plane, but subscribing to MQTT topics requires an MQTT client, which the IoT Device SDK provides.

Here’s how you can subscribe to a topic using the AWS IoT Device SDK v2 for Node.js:

1. Install the SDK:

First, install the AWS IoT Device SDK v2 for JavaScript:

2. Subscribing to a Topic:

You can subscribe to a topic using the mqtt module of the AWS IoT Device SDK. Here’s an example:

const iot = require('aws-iot-device-sdk-v2'); const mqtt = iot.mqtt; const client = new mqtt.MqttClient(); const connection = client.new_connection({ client_id: 'your-client-id', host_name: 'your-iot-endpoint', port: 8883, // TLS port clean_session: true, use_websocket: false, tls_ctx: mqtt.tls_ctx_options.create_client_with_mtls( 'path-to-certificate.pem', 'path-to-private-key.pem' ), }); async function connectAndSubscribe() { await connection.connect(); connection.subscribe('your/topic', mqtt.QoS.AtLeastOnce, (topic, payload) => { const message = new TextDecoder('utf-8').decode(payload); console.log(`Received message on topic ${topic}: ${message}`); }); console.log('Subscribed to the topic'); } connectAndSubscribe().catch(console.error);

 

Support On Demand!

QA Automation