mqtt
The mqtt is the MQTT client module.
In JSH applications, you normally use:
const mqtt = require('mqtt');This module is event-driven and auto-connects when a Client is created.
Client
MQTT client object.
Creation
new Client(options)Options
| Option | Type | Default | Description |
|---|---|---|---|
| servers | String[] | MQTT broker URLs (e.g. tcp://127.0.0.1:1883) | |
| username | String | Username for broker authentication | |
| password | String | Password for broker authentication | |
| keepAlive | Number | 30 | Keep alive in seconds |
| connectRetryDelay | Number | 0 | Reconnect delay in milliseconds |
| cleanStartOnInitialConnection | Boolean | false | MQTT v5 clean start on first connection |
| connectTimeout | Number | 0 | Connect timeout in milliseconds |
Usage example
| |
Methods
publish()
Publishes a message to a topic.
Syntax
publish(topic, message[, options])Parameters
topicStringmessageString|Uint8Array|Object|ArrayoptionsObject(optional)
| Option | Type | Default | Description |
|---|---|---|---|
| qos | Number | 0 | QoS level |
| retain | Boolean | false | Retain flag |
| properties | Object | MQTT v5 publish properties |
options.properties fields:
| Property | Type | Description |
|---|---|---|
| payloadFormat | Number | Payload format indicator |
| messageExpiry | Number | Expiry interval |
| contentType | String | Content type |
| responseTopic | String | Response topic |
| correlationData | String | Converted to bytes |
| topicAlias | Number | Topic alias |
| subscriptionIdentifier | Number | Subscription identifier |
| user | Object | User properties (key: value) |
Return value
None. Result is delivered by published or error events.
subscribe()
Subscribes to a topic.
Syntax
subscribe(topic[, options])Parameters
topicStringoptionsObject(optional)
| Option | Type | Default | Description |
|---|---|---|---|
| qos | Number | 1 | QoS level |
| retainHandling | Number | MQTT v5 retain handling | |
| noLocal | Boolean | false | Whether to suppress messages published by the same client |
| retainAsPublished | Boolean | false | Whether to preserve the retain flag from the broker |
| properties | Object | MQTT v5 subscribe properties |
options.properties fields:
| Property | Type | Description |
|---|---|---|
| subscriptionIdentifier | Number | Subscription identifier |
| user | Object | User properties (key: value) |
Return value
None. Result is delivered by subscribed or error events.
Usage example
client.subscribe('test/topic', {
qos: 0,
properties: {
subscriptionIdentifier: 7,
user: {
source: 'example',
},
},
});unsubscribe()
Unsubscribes from a topic.
Syntax
unsubscribe(topic[, options])Parameters
topicStringoptionsObject(optional)
| Option | Type | Description |
|---|---|---|
| properties | Object | MQTT v5 unsubscribe properties |
options.properties fields:
| Property | Type | Description |
|---|---|---|
| user | Object | User properties (key: value) |
Return value
None. Result is delivered by unsubscribed or error events.
Usage example
client.unsubscribe('test/topic', {
properties: {
user: {
source: 'example',
},
},
});close()
Closes the client connection.
Syntax
close()Return value
None. Emits close event.
Events
open
Emitted after the client is connected.
client.on('open', () => { ... })message
Emitted when a subscribed message is received.
client.on('message', (msg) => { ... })msg fields:
| Property | Type | Description |
|---|---|---|
| topic | String | Topic name |
| payload | Buffer | Binary-safe message payload |
| payloadText | String | UTF-8 decoded text convenience field |
| properties | Object | MQTT v5 publish properties |
msg.properties fields:
| Property | Type | Description |
|---|---|---|
| payloadFormat | Number | Payload format indicator |
| messageExpiry | Number | Expiry interval |
| contentType | String | Content type |
| responseTopic | String | Response topic |
| correlationData | Buffer | Binary-safe correlation data |
| topicAlias | Number | Topic alias |
| subscriptionIdentifier | Number | Subscription identifier |
| user | Object | User properties |
For text messages, use msg.payloadText or msg.payload.toString().
For binary messages, inspect msg.payload directly.
client.on('message', (msg) => {
console.println('Payload is buffer:', Buffer.isBuffer(msg.payload));
console.println('Payload bytes:', Array.from(msg.payload).join(','));
});MQTT v5 publish properties are available as msg.properties.
client.on('message', (msg) => {
console.println('Content type:', msg.properties.contentType);
console.println('Response topic:', msg.properties.responseTopic);
console.println('Correlation data:', msg.properties.correlationData.toString());
console.println('User source:', msg.properties.user.source);
});subscribed
Emitted when subscription ack is received.
client.on('subscribed', (topic, reason) => { ... })topicStringreasonNumber(MQTT reason code)
published
Emitted when publish ack is received.
client.on('published', (topic, reason) => { ... })topicStringreasonNumber(MQTT reason code)
unsubscribed
Emitted when unsubscribe ack is received.
client.on('unsubscribed', (topic, reason) => { ... })topicStringreasonNumber(MQTT reason code)
error
Emitted when connection, subscribe, unsubscribe, or publish fails.
client.on('error', (err) => { ... })errError
If publish(), subscribe(), or unsubscribe() is called before the client is connected or after close(), the error is delivered through the error event.
close
Emitted when close() is called.
client.on('close', () => { ... })MQTT v5 write properties example
This example writes to db/write/{table} and sets MQTT v5 user properties documented in MQTT v5 write API.
| |