MQTT.js

MQTT.js

JavaScript实现的轻量级MQTT客户端库

MQTT.js是一个用JavaScript实现的MQTT协议客户端库,支持Node.js和浏览器环境。该库实现了MQTT的核心功能,包括发布/订阅、QoS和保留消息等。MQTT.js具有轻量、高效和易用的特点,适用于物联网和实时通信应用。它支持MQTT 3.1.1和5.0版本协议,并提供命令行工具便于开发调试。

MQTTJavaScriptNode.jsWebSocket消息队列Github开源项目

mqtt.js

Github Test Status codecov

Maintenance PRs Welcome

node npm NPM Downloads

MQTT.js is a client library for the MQTT protocol, written in JavaScript for node.js and the browser.

Table of Contents

MQTT.js is an OPEN Open Source Project, see the Contributing section to find out what this means.

JavaScript Style
Guide

<a name="notes"></a>

Important notes for existing users

v5.0.0 (07/2023)

  • Removes support for all end of life node versions (v12 and v14), and now supports node v18 and v20.
  • Completely rewritten in Typescript 🚀.
  • When creating MqttClient instance new is now required.

v4.0.0 (Released 04/2020) removes support for all end of life node versions, and now supports node v12 and v14. It also adds improvements to debug logging, along with some feature additions.

As a breaking change, by default a error handler is built into the MQTT.js client, so if any errors are emitted and the user has not created an event handler on the client for errors, the client will not break as a result of unhandled errors. Additionally, typical TLS errors like ECONNREFUSED, ECONNRESET have been added to a list of TLS errors that will be emitted from the MQTT.js client, and so can be handled as connection errors.

v3.0.0 adds support for MQTT 5, support for node v10.x, and many fixes to improve reliability.

Note: MQTT v5 support is experimental as it has not been implemented by brokers yet.

v2.0.0 removes support for node v0.8, v0.10 and v0.12, and it is 3x faster in sending packets. It also removes all the deprecated functionality in v1.0.0, mainly mqtt.createConnection and mqtt.Server. From v2.0.0, subscriptions are restored upon reconnection if clean: true. v1.x.x is now in LTS, and it will keep being supported as long as there are v0.8, v0.10 and v0.12 users.

As a breaking change, the encoding option in the old client is removed, and now everything is UTF-8 with the exception of the password in the CONNECT message and payload in the PUBLISH message, which are Buffer.

Another breaking change is that MQTT.js now defaults to MQTT v3.1.1, so to support old brokers, please read the client options doc.

v1.0.0 improves the overall architecture of the project, which is now split into three components: MQTT.js keeps the Client, mqtt-connection includes the barebone Connection code for server-side usage, and mqtt-packet includes the protocol parser and generator. The new Client improves performance by a 30% factor, embeds Websocket support (MOWS is now deprecated), and it has a better support for QoS 1 and 2. The previous API is still supported but deprecated, as such, it is not documented in this README.

<a name="install"></a>

Installation

npm install mqtt --save

<a name="example"></a>

Example

For the sake of simplicity, let's put the subscriber and the publisher in the same file:

const mqtt = require("mqtt"); const client = mqtt.connect("mqtt://test.mosquitto.org"); client.on("connect", () => { client.subscribe("presence", (err) => { if (!err) { client.publish("presence", "Hello mqtt"); } }); }); client.on("message", (topic, message) => { // message is Buffer console.log(message.toString()); client.end(); });

output:

Hello mqtt

<a name="example-react-native"></a>

React Native

MQTT.js can be used in React Native applications. To use it, see the React Native example

If you want to run your own MQTT broker, you can use Mosquitto or Aedes-cli, and launch it.

You can also use a test instance: test.mosquitto.org.

If you do not want to install a separate broker, you can try using the Aedes.

<a name="import_styles"></a>

Import styles

CommonJS (Require)

const mqtt = require("mqtt") // require mqtt const client = mqtt.connect("mqtt://test.mosquitto.org") // create a client

ES6 Modules (Import)

Default import

import mqtt from "mqtt"; // import namespace "mqtt" let client = mqtt.connect("mqtt://test.mosquitto.org"); // create a client

Importing individual components

import { connect } from "mqtt"; // import connect from mqtt let client = connect("mqtt://test.mosquitto.org"); // create a client

<a name="cli"></a>

Command Line Tools

MQTT.js bundles a command to interact with a broker. In order to have it available on your path, you should install MQTT.js globally:

npm install mqtt -g

Then, on one terminal

mqtt sub -t 'hello' -h 'test.mosquitto.org' -v

On another

mqtt pub -t 'hello' -h 'test.mosquitto.org' -m 'from MQTT.js'

See mqtt help <command> for the command help.

<a name="debug"></a>

Debug Logs

MQTT.js uses the debug package for debugging purposes. To enable debug logs, add the following environment variable on runtime :

# (example using PowerShell, the VS Code default) $env:DEBUG='mqttjs*'

<a name="reconnecting"></a>

About Reconnection

An important part of any websocket connection is what to do when a connection drops off and the client needs to reconnect. MQTT has built-in reconnection support that can be configured to behave in ways that suit the application.

Refresh Authentication Options / Signed Urls with transformWsUrl (Websocket Only)

When an mqtt connection drops and needs to reconnect, it's common to require that any authentication associated with the connection is kept current with the underlying auth mechanism. For instance some applications may pass an auth token with connection options on the initial connection, while other cloud services may require a url be signed with each connection.

By the time the reconnect happens in the application lifecycle, the original auth data may have expired.

To address this we can use a hook called transformWsUrl to manipulate either of the connection url or the client options at the time of a reconnect.

Example (update clientId & username on each reconnect):

const transformWsUrl = (url, options, client) => { client.options.username = `token=${this.get_current_auth_token()}`; client.options.clientId = `${this.get_updated_clientId()}`; return `${this.get_signed_cloud_url(url)}`; } const connection = await mqtt.connectAsync(<wss url>, { ..., transformWsUrl: transformUrl, });

Now every time a new WebSocket connection is opened (hopefully not too often), we will get a fresh signed url or fresh auth token data.

Note: Currently this hook does not support promises, meaning that in order to use the latest auth token, you must have some outside mechanism running that handles application-level authentication refreshing so that the websocket connection can simply grab the latest valid token or signed url.

Customize Websockets with createWebsocket (Websocket Only)

When you need to add a custom websocket subprotocol or header to open a connection through a proxy with custom authentication this callback allows you to create your own instance of a websocket which will be used in the mqtt client.

const createWebsocket = (url, websocketSubProtocols, options) => { const subProtocols = [ websocketSubProtocols[0], 'myCustomSubprotocolOrOAuthToken', ] return new WebSocket(url, subProtocols) } const client = await mqtt.connectAsync(<wss url>, { ..., createWebsocket: createWebsocket, });

Enabling Reconnection with reconnectPeriod option

To ensure that the mqtt client automatically tries to reconnect when the connection is dropped, you must set the client option reconnectPeriod to a value greater than 0. A value of 0 will disable reconnection and then terminate the final connection when it drops.

The default value is 1000 ms which means it will try to reconnect 1 second after losing the connection.

<a name="topicalias"></a>

About Topic Alias Management

Enabling automatic Topic Alias using

If the client sets the option autoUseTopicAlias:true then MQTT.js uses existing topic alias automatically.

example scenario:

1. PUBLISH topic:'t1', ta:1 (register) 2. PUBLISH topic:'t1' -> topic:'', ta:1 (auto use existing map entry) 3. PUBLISH topic:'t2', ta:1 (register overwrite) 4. PUBLISH topic:'t2' -> topic:'', ta:1 (auto use existing map entry based on the receent map) 5. PUBLISH topic:'t1' (t1 is no longer mapped to ta:1)

User doesn't need to manage which topic is mapped to which topic alias. If the user want to register topic alias, then publish topic with topic alias. If the user want to use topic alias, then publish topic without topic alias. If there is a mapped topic alias then added it as a property and update the topic to empty string.

Enabling automatic Topic Alias assign

If the client sets the option autoAssignTopicAlias:true then MQTT.js uses existing topic alias automatically. If no topic alias exists, then assign a new vacant topic alias automatically. If topic alias is fully used, then LRU(Least Recently Used) topic-alias entry is overwritten.

example scenario:

The broker returns CONNACK (TopicAliasMaximum:3) 1. PUBLISH topic:'t1' -> 't1', ta:1 (auto assign t1:1 and register) 2. PUBLISH topic:'t1' -> '' , ta:1 (auto use existing map entry) 3. PUBLISH topic:'t2' -> 't2', ta:2 (auto assign t1:2 and register. 2 was vacant) 4. PUBLISH topic:'t3' -> 't3', ta:3 (auto assign t1:3 and register. 3 was vacant) 5. PUBLISH topic:'t4' -> 't4', ta:1 (LRU entry is overwritten)

Also user can manually register topic-alias pair using PUBLISH topic:'some', ta:X. It works well with automatic topic alias assign.

<a name="api"></a>

API


<a name="connect"></a>

mqtt.connect([url], options)

Connects to the broker specified by the given url and options and returns a Client.

The URL can be on the following protocols: 'mqtt', 'mqtts', 'tcp', 'tls', 'ws', 'wss', 'wxs', 'alis'. If you are trying to connect to a unix socket just append the +unix suffix to the protocol (ex: mqtt+unix). This will set the unixSocket property automatically.

The URL can also be an object as returned by URL.parse(), in that case the two objects are merged, i.e. you can pass a single object with both the URL and the connect options.

You can also specify a servers options with content: [{ host: 'localhost', port: 1883 }, ... ], in that case that array is iterated at every connect.

For all MQTT-related options, see the Client constructor.

<a name="connect-async"></a>

connectAsync([url], options)

Asynchronous wrapper around the connect function.

Returns a Promise that resolves to a mqtt.Client instance when the client fires a 'connect' or 'end' event, or rejects with an error if the 'error' is fired.

Note that the manualConnect option will cause the promise returned by this function to never resolve or reject as the underlying client never fires any events.


<a name="client"></a>

mqtt.Client(streamBuilder, options)

The Client class wraps a client connection to an MQTT broker over an arbitrary transport method (TCP, TLS, WebSocket, ecc). Client is an EventEmitter that has it's own events

Client automatically handles the following:

  • Regular server pings
  • QoS flow
  • Automatic reconnections
  • Start publishing before being connected

The arguments are:

  • streamBuilder is a function that returns a subclass of the Stream class that supports the connect event. Typically a net.Socket.
  • options is the client connection options (see: the connect packet). Defaults:
    • wsOptions: is the WebSocket connection options. Default is {}. It's specific for WebSockets. For possible options have a look at: https://github.com/websockets/ws/blob/master/doc/ws.md.
    • keepalive: 60 seconds, set to 0 to disable
    • reschedulePings: reschedule ping messages after sending packets (default true)
    • clientId: 'mqttjs_' + Math.random().toString(16).substr(2, 8)
    • protocolId: 'MQTT'
    • protocolVersion: 4
    • clean: true, set to false to receive QoS 1 and 2 messages while offline
    • reconnectPeriod: 1000 milliseconds, interval between two reconnections. Disable auto reconnect by setting to 0.
    • connectTimeout: 30 * 1000 milliseconds, time to wait before a CONNACK is received
    • username: the username required by your broker, if any
    • password: the password required by your broker, if any
    • incomingStore: a Store for the incoming packets
    • outgoingStore: a Store for the outgoing packets
    • queueQoSZero: if connection is broken, queue outgoing

编辑推荐精选

Trae

Trae

字节跳动发布的AI编程神器IDE

Trae是一种自适应的集成开发环境(IDE),通过自动化和多元协作改变开发流程。利用Trae,团队能够更快速、精确地编写和部署代码,从而提高编程效率和项目交付速度。Trae具备上下文感知和代码自动完成功能,是提升开发效率的理想工具。

AI工具TraeAI IDE协作生产力转型热门
问小白

问小白

全能AI智能助手,随时解答生活与工作的多样问题

问小白,由元石科技研发的AI智能助手,快速准确地解答各种生活和工作问题,包括但不限于搜索、规划和社交互动,帮助用户在日常生活中提高效率,轻松管理个人事务。

热门AI助手AI对话AI工具聊天机器人
Transly

Transly

实时语音翻译/同声传译工具

Transly是一个多场景的AI大语言模型驱动的同声传译、专业翻译助手,它拥有超精准的音频识别翻译能力,几乎零延迟的使用体验和支持多国语言可以让你带它走遍全球,无论你是留学生、商务人士、韩剧美剧爱好者,还是出国游玩、多国会议、跨国追星等等,都可以满足你所有需要同传的场景需求,线上线下通用,扫除语言障碍,让全世界的语言交流不再有国界。

讯飞智文

讯飞智文

一键生成PPT和Word,让学习生活更轻松

讯飞智文是一个利用 AI 技术的项目,能够帮助用户生成 PPT 以及各类文档。无论是商业领域的市场分析报告、年度目标制定,还是学生群体的职业生涯规划、实习避坑指南,亦或是活动策划、旅游攻略等内容,它都能提供支持,帮助用户精准表达,轻松呈现各种信息。

AI办公办公工具AI工具讯飞智文AI在线生成PPTAI撰写助手多语种文档生成AI自动配图热门
讯飞星火

讯飞星火

深度推理能力全新升级,全面对标OpenAI o1

科大讯飞的星火大模型,支持语言理解、知识问答和文本创作等多功能,适用于多种文件和业务场景,提升办公和日常生活的效率。讯飞星火是一个提供丰富智能服务的平台,涵盖科技资讯、图像创作、写作辅助、编程解答、科研文献解读等功能,能为不同需求的用户提供便捷高效的帮助,助力用户轻松获取信息、解决问题,满足多样化使用场景。

热门AI开发模型训练AI工具讯飞星火大模型智能问答内容创作多语种支持智慧生活
Spark-TTS

Spark-TTS

一种基于大语言模型的高效单流解耦语音令牌文本到语音合成模型

Spark-TTS 是一个基于 PyTorch 的开源文本到语音合成项目,由多个知名机构联合参与。该项目提供了高效的 LLM(大语言模型)驱动的语音合成方案,支持语音克隆和语音创建功能,可通过命令行界面(CLI)和 Web UI 两种方式使用。用户可以根据需求调整语音的性别、音高、速度等参数,生成高质量的语音。该项目适用于多种场景,如有声读物制作、智能语音助手开发等。

咔片PPT

咔片PPT

AI助力,做PPT更简单!

咔片是一款轻量化在线演示设计工具,借助 AI 技术,实现从内容生成到智能设计的一站式 PPT 制作服务。支持多种文档格式导入生成 PPT,提供海量模板、智能美化、素材替换等功能,适用于销售、教师、学生等各类人群,能高效制作出高品质 PPT,满足不同场景演示需求。

讯飞绘文

讯飞绘文

选题、配图、成文,一站式创作,让内容运营更高效

讯飞绘文,一个AI集成平台,支持写作、选题、配图、排版和发布。高效生成适用于各类媒体的定制内容,加速品牌传播,提升内容营销效果。

热门AI辅助写作AI工具讯飞绘文内容运营AI创作个性化文章多平台分发AI助手
材料星

材料星

专业的AI公文写作平台,公文写作神器

AI 材料星,专业的 AI 公文写作辅助平台,为体制内工作人员提供高效的公文写作解决方案。拥有海量公文文库、9 大核心 AI 功能,支持 30 + 文稿类型生成,助力快速完成领导讲话、工作总结、述职报告等材料,提升办公效率,是体制打工人的得力写作神器。

openai-agents-python

openai-agents-python

OpenAI Agents SDK,助力开发者便捷使用 OpenAI 相关功能。

openai-agents-python 是 OpenAI 推出的一款强大 Python SDK,它为开发者提供了与 OpenAI 模型交互的高效工具,支持工具调用、结果处理、追踪等功能,涵盖多种应用场景,如研究助手、财务研究等,能显著提升开发效率,让开发者更轻松地利用 OpenAI 的技术优势。

下拉加载更多