Node.js
MQTT.js is the standard MQTT client for Node.js and the browser.
Install
bash
npm install mqttPublish and subscribe
js
// index.mjs
import mqtt from 'mqtt'
const client = mqtt.connect('mqtts://broker.connectmq.com:8883', {
clientId: `${process.env.CMQ_CLIENT_ID}_node-service`, // issued client ID + "_" + suffix
username: process.env.CMQ_USERNAME,
password: process.env.CMQ_PASSWORD,
protocolVersion: 5,
keepalive: 60,
})
client.on('connect', () => {
console.log('connected')
client.subscribe('acme/istanbul/+/+/+/telemetry', { qos: 1 })
setInterval(() => {
const reading = { temperature: 41.8, cycleTime: 12.4 }
client.publish('acme/istanbul/assembly/line1/robot-01/telemetry', JSON.stringify(reading), { qos: 1 })
}, 5000)
})
client.on('message', (topic, payload) => console.log(topic, payload.toString()))
client.on('error', (err) => console.error(err.message))bash
CMQ_CLIENT_ID=connectmq_client_123456 CMQ_USERNAME=cmq_xxxx CMQ_PASSWORD='...' node index.mjsNotes
- MQTT.js reconnects automatically. If you see a connect/disconnect loop, another client is using the same client ID: see Client IDs & sessions.
- Wildcards:
+matches one level,#matches the rest. Wildcard subscriptions are part of every plan; shared subscriptions ($share/group/topic) need a Basic or Scale plan. - For a browser app, use the same library over WebSockets: Browser (WebSockets).