npm i mqtt
<script src="https://unpkg.com/mqtt/dist/mqtt.min.js"></script><script>// will initialize an mqtt variable globally.console.log(mqtt)</script>
npm i mqtt -gmqtt helpMQTT.js command line interface, available commands are:* publish publish a message to the broker* subscribe subscribe for updates from the broker* version the current MQTT.js version* help help about commandsLaunch 'mqtt help [command]' to know more about the commands.
const mqtt = require('mqtt');/*** MQTT 5.0 TCP Connection Example*/// ============ Connection Configuration ============const serverUri = 'mqtt://mqtt-xxx.mqtt.tencenttdmq.com:1883';const clientId = 'QuickStart';const username = 'YOUR_USERNAME';const password = 'YOUR_PASSWORD';const pubTopic = 'home/test';const topicFilters = ['home/test', 'home/#', 'home/+'];const qos = [1, 1, 1];// Configure connection optionsconst options = {clientId: clientId,username: username,password: password,protocolVersion: 5, // MQTT 5.0clean: true,reconnectPeriod: 0, // Disable automatic reconnection};// Create a client and connectconst client = mqtt.connect(serverUri, options);// Connection successfulclient.on('connect', async () => {console.log('Connected');try {// 2. Subscribefor (let i = 0; i < topicFilters.length; i++) {await new Promise((resolve, reject) => {client.subscribe(topicFilters[i], { qos: qos[i] }, (err) => {if (err) reject(err);else resolve();});});}console.log('Subscribed');// 3. Publishfor (let i = 1; i <= 16; i++) {await new Promise((resolve, reject) => {client.publish(pubTopic, `Message #${i}`, { qos: 1 }, (err) => {if (err) reject(err);else resolve();});});await new Promise(resolve => setTimeout(resolve, 500));}console.log('Publish completed');// 4. Wait to receiveawait new Promise(resolve => setTimeout(resolve, 2000));// 5. Disconnectclient.end();console.log('Disconnected');} catch (error) {console.error('Error:', error.message);client.end();}});// Message receiving and processingclient.on('message', (topic, message) => {console.log(`Received message: ${topic} -> ${message.toString()}`);});// Error Handlingclient.on('error', (error) => {console.error('Error:', error.message);});
const mqtt = require('mqtt');const fs = require('fs');const tls = require('tls');/*** MQTT 5.0 TLS Encrypted Connection Example*/// ============ Connection Configuration ============const serverUri = 'mqtts://mqtt-xxx.mqtt.tencenttdmq.com:8883';const clientId = 'QuickStart';const username = 'YOUR_USERNAME';const password = 'YOUR_PASSWORD';const pubTopic = 'home/test';const topicFilters = ['home/test', 'home/#', 'home/+'];const qos = [1, 1, 1];// CA certificate path (optional, used to verify server certificate)const caCertPath = null; // e.g., '/path/to/ca.crt'// Configure connection options (with TLS)const options = {clientId: clientId,username: username,password: password,protocolVersion: 5, // MQTT 5.0clean: true,reconnectPeriod: 0, // Disable automatic reconnection// TLS ConfigurationrejectUnauthorized: true, // Production environment: verify server certificate// If a CA certificate is provided, load itca: caCertPath ? [fs.readFileSync(caCertPath)] : undefined,// Custom certificate verificationcheckServerIdentity: (host, cert) => {return validateServerCertificate(host, cert);}};/*** Verify server certificate*/function validateServerCertificate(host, cert) {// 1. Check the certificate validity periodconst now = new Date();const validFrom = new Date(cert.valid_from);const validTo = new Date(cert.valid_to);if (now < validFrom || now > validTo) {const error = new Error(`Certificate verification failed: the certificate has expired or is not yet valid (Validity period: ${validFrom} - ${validTo})`);console.error(error.message);return error;}// 2. Check the topic name (Optional, depending on actual requirements)// const expectedSubject = 'CN=*.mqtt.tencenttdmq.com';// if (!cert.subject.CN || !cert.subject.CN.includes('mqtt.tencenttdmq.com')) {// const error = new Error(`Certificate verification failed: Subject mismatch (Actual: ${cert.subject.CN})`);// console.error(error.message);// return error;// }// 3. Use default certificate chain verificationconst err = tls.checkServerIdentity(host, cert);if (err) {console.error('Certificate verification failed:', err.message);return err;}console.log('Certificate verification passed');return undefined;}// Create a client and connectconst client = mqtt.connect(serverUri, options);// Connection successfulclient.on('connect', async () => {console.log('Connected (TLS encrypted)');try {// 2. Subscribefor (let i = 0; i < topicFilters.length; i++) {await new Promise((resolve, reject) => {client.subscribe(topicFilters[i], { qos: qos[i] }, (err) => {if (err) reject(err);else resolve();});});}console.log('Subscribed');// 3. Publishfor (let i = 1; i <= 16; i++) {await new Promise((resolve, reject) => {client.publish(pubTopic, `Message #${i}`, { qos: 1 }, (err) => {if (err) reject(err);else resolve();});});await new Promise(resolve => setTimeout(resolve, 500));}console.log('Publish completed');// 4. Wait to receiveawait new Promise(resolve => setTimeout(resolve, 2000));// 5. Disconnectclient.end();console.log('Disconnected');} catch (error) {console.error('Error:', error.message);client.end();}});// Message receiving and processingclient.on('message', (topic, message) => {console.log(`Received message: ${topic} -> ${message.toString()}`);});// Error Handlingclient.on('error', (error) => {console.error('Error:', error.message);});
const mqtt = require('mqtt');/*** MQTT 3.1.1 TCP Connection Example*/// ============ Connection Configuration ============const serverUri = 'mqtt://mqtt-xxx.mqtt.tencenttdmq.com:1883';const clientId = 'QuickStart';const username = 'YOUR_USERNAME';const password = 'YOUR_PASSWORD';const pubTopic = 'home/test';const topicFilters = ['home/test', 'home/#', 'home/+'];const qos = [1, 1, 1];// Configure connection optionsconst options = {clientId: clientId,username: username,password: password,protocolVersion: 4, // MQTT 3.1.1clean: true,reconnectPeriod: 0, // Disable automatic reconnection};// Create a client and connectconst client = mqtt.connect(serverUri, options);// Connection successfulclient.on('connect', async () => {console.log('Connected');try {// 2. Subscribefor (let i = 0; i < topicFilters.length; i++) {await new Promise((resolve, reject) => {client.subscribe(topicFilters[i], { qos: qos[i] }, (err) => {if (err) reject(err);else resolve();});});}console.log('Subscribed');// 3. Publishfor (let i = 1; i <= 16; i++) {await new Promise((resolve, reject) => {client.publish(pubTopic, `Message #${i}`, { qos: 1 }, (err) => {if (err) reject(err);else resolve();});});await new Promise(resolve => setTimeout(resolve, 500));}console.log('Publish completed');// 4. Wait to receiveawait new Promise(resolve => setTimeout(resolve, 2000));// 5. Disconnectclient.end();console.log('Disconnected');} catch (error) {console.error('Error:', error.message);client.end();}});// Message receiving and processingclient.on('message', (topic, message) => {console.log(`Received message: ${topic} -> ${message.toString()}`);});// Error Handlingclient.on('error', (error) => {console.error('Error:', error.message);});
const mqtt = require('mqtt');const fs = require('fs');const tls = require('tls');/*** MQTT 3.1.1 TLS Encrypted Connection Example*/// ============ Connection Configuration ============const serverUri = 'mqtts://mqtt-xxx.mqtt.tencenttdmq.com:8883';const clientId = 'QuickStart';const username = 'YOUR_USERNAME';const password = 'YOUR_PASSWORD';const pubTopic = 'home/test';const topicFilters = ['home/test', 'home/#', 'home/+'];const qos = [1, 1, 1];// CA certificate path (optional, used to verify server certificate)const caCertPath = null; // e.g., '/path/to/ca.crt'// Configure connection options (with TLS)const options = {clientId: clientId,username: username,password: password,protocolVersion: 4, // MQTT 3.1.1clean: true,reconnectPeriod: 0, // Disable automatic reconnection// TLS ConfigurationrejectUnauthorized: true, // Production environment: verify server certificate// If a CA certificate is provided, load itca: caCertPath ? [fs.readFileSync(caCertPath)] : undefined,// Custom certificate verificationcheckServerIdentity: (host, cert) => {return validateServerCertificate(host, cert);}};/*** Verify server certificate*/function validateServerCertificate(host, cert) {// 1. Check the certificate validity periodconst now = new Date();const validFrom = new Date(cert.valid_from);const validTo = new Date(cert.valid_to);if (now < validFrom || now > validTo) {const error = new Error(`Certificate verification failed: the certificate has expired or is not yet valid (Validity period: ${validFrom} - ${validTo})`);console.error(error.message);return error;}// 2. Check the topic name (Optional, depending on actual requirements)// const expectedSubject = 'CN=*.mqtt.tencenttdmq.com';// if (!cert.subject.CN || !cert.subject.CN.includes('mqtt.tencenttdmq.com')) {// const error = new Error(`Certificate verification failed: Subject mismatch (Actual: ${cert.subject.CN})`);// console.error(error.message);// return error;// }// 3. Use default certificate chain verificationconst err = tls.checkServerIdentity(host, cert);if (err) {console.error('Certificate verification failed:', err.message);return err;}console.log('Certificate verification passed');return undefined;}// Create a client and connectconst client = mqtt.connect(serverUri, options);// Connection successfulclient.on('connect', async () => {console.log('Connected (TLS encrypted)');try {// 2. Subscribefor (let i = 0; i < topicFilters.length; i++) {await new Promise((resolve, reject) => {client.subscribe(topicFilters[i], { qos: qos[i] }, (err) => {if (err) reject(err);else resolve();});});}console.log('Subscribed');// 3. Publishfor (let i = 1; i <= 16; i++) {await new Promise((resolve, reject) => {client.publish(pubTopic, `Message #${i}`, { qos: 1 }, (err) => {if (err) reject(err);else resolve();});});await new Promise(resolve => setTimeout(resolve, 500));}console.log('Publish completed');// 4. Wait to receiveawait new Promise(resolve => setTimeout(resolve, 2000));// 5. Disconnectclient.end();console.log('Disconnected');} catch (error) {console.error('Error:', error.message);client.end();}});// Message receiving and processingclient.on('message', (topic, message) => {console.log(`Received message: ${topic} -> ${message.toString()}`);});// Error Handlingclient.on('error', (error) => {console.error('Error:', error.message);});
Parameter | Description |
topic | Copy the first-level MQTT Topic from the Topic Prefix page in the cluster details console. |
connectUrl | broker connection address can be copied from the Basic Information > Access Information section of the target cluster in the console, as shown below. Format: mqtt-xxx-gz.mqtt.qcloud.tencenttdmq.com:1883. |
clientId | Client ID is obtained from the Client Management page in the cluster details page on the console. |
username | Connection username can be copied from the Authentication Management page on the cluster details console. |
password | The password matching the Connection Username can be copied from the Authentication Management page on the cluster details console. |
masukan