Open source

Client.on()

The on() method registers event handlers for various MQTT client lifecycle and message events. All event handlers execute in the context of the k6 VU event loop.

Signature

JavaScript
client.on(event, listener)

Parameters

ParameterTypeDescription
eventstringEvent name (connect, message, end, reconnect, error)
listenerfunctionCallback function to handle the event

Events

connect

Triggered when the client successfully connects to the broker.

Signature

JavaScript
client.on("connect", () => {
  // Connection established
})

message

Triggered when a message is received on a subscribed topic.

Signature

JavaScript
client.on("message", (topic, payload) => {
  // Handle received message
})

Parameters

ParameterTypeDescription
topicstringThe topic the message was received on
payloadArrayBufferThe message payload as binary data

end

Triggered when the client disconnects from the broker.

Signature

JavaScript
client.on("end", () => {
  // Connection closed
})

reconnect

Triggered when the client attempts to reconnect to the broker.

Signature

JavaScript
client.on("reconnect", () => {
  // Reconnection attempt
})

error

Triggered when an error occurs during any MQTT operation.

Signature

JavaScript
client.on("error", (error) => {
  // Handle error
})

Parameters

ParameterTypeDescription
errorobjectError object
error.namestringAlways “MQTTError”
error.messagestringError description
error.methodstringThe method where the error occurred