MQTT JavaScript client library

MQTT.jsMQTT JavaScript Client Library - 图1 (opens new window) is a module written in JavaScript that implements the MQTT protocol client function and can be used in browsers and Node.js environments.

Due to the single-threaded nature of JavaScript, MQTT.js is a fully asynchronous MQTT client. MQTT.js supports MQTT and MQTT over WebSocket. The support in different operating environments is as follows:

  • Browser environment: MQTT over WebSocket (including WeChat applet, Alipay applet and other customized browser environments)
  • Node.js environment: MQTT, MQTT over WebSocket

Except for a small number of connection parameters that is different in different environments, the other APIs are the same.

Install using npm :

  1. npm i mqtt

Install using CDN (browser):

  1. <script src="https://unpkg.com/mqtt/dist/mqtt.min.js"></script>
  2. <script>
  3. // Initialize a mqtt variable globally
  4. console.log(mqtt)
  5. </script>

In the environment where Node.js is installed, you can use MQTT.js global ly in the form of a command line of npm i mqtt -g command.

  1. npm i mqtt -g
  2. mqtt help
  3. > MQTT.js command line interface, available commands are:
  4. * publish publish a message to the broker
  5. * subscribe subscribe for updates from the broker
  6. * version the current MQTT.js version
  7. * help help about commands
  8. > Launch 'mqtt help [command]' to know more about the commands.

MQTT.js usage example

This example contains the complete code of MQTT.js in JavaScrip language connecting EMQ X Broker, sending and receiving messages:

  1. // const mqtt = require('mqtt')
  2. import mqtt from 'mqtt'
  3. // connection option
  4. const options = {
  5. clean: true, // retain session
  6. connectTimeout: 4000, // Timeout period
  7. // Authentication information
  8. clientId: 'emqx_test',
  9. username: 'emqx_test',
  10. password: 'emqx_test',
  11. }
  12. // Connect string, and specify the connection method by the protocol
  13. // ws Unencrypted WebSocket connection
  14. // wss Encrypted WebSocket connection
  15. // mqtt Unencrypted TCP connection
  16. // mqtts Encrypted TCP connection
  17. // wxs WeChat applet connection
  18. // alis Alipay applet connection
  19. const connectUrl = 'wss://broker.emqx.io:8084/mqtt'
  20. const client = mqtt.connect(connectUrl, options)
  21. client.on('reconnect', (error) => {
  22. console.log('reconnecting:', error)
  23. })
  24. client.on('error', (error) => {
  25. console.log('Connection failed:', error)
  26. })
  27. client.on('message', (topic, message) => {
  28. console.log('receive message:', topic, message.toString())
  29. })

MQTT.js MQTT 5.0 support

Currently, MQTT.js has fully supported MQTT 5.0.