Node.js is a JavaScript runtime environment Chrome V8 engine Before the advent of Node.js, JavaScript was usually used as a client-side programming language, and programs written in JavaScript were often run on the user's browser. With the advent of Node.js, JavaScript can also be used for server-side programming.

MQTT is a lightweight IoT messaging protocol based on the publish/subscribe model. It can provide real-time and reliable messaging services for networked devices with very little code and bandwidth. It is widely used in the Internet of Things, mobile Internet, and intelligence. Hardware, car networking, power and energy industries.

This article mainly introduces how to use MQTT in the Node.js project to realize the functions of connecting, subscribing, unsubscribing, sending and receiving messages between the client and the MQTT server.

MQTT client library selection

MQTT.js is a client library of the MQTT protocol, written in JavaScript and used in Node.js and browser environments. It is currently the most widely used MQTT client library in the JavaScript ecosystem.

Project initialization

Confirm Node.js version

This project uses Node.js v14.14.0 for development and testing. Readers can confirm the version of Node.js with the following command

node --version

v14.14.0

Use npm to install the MQTT.js client library

# 新建项目
npm init -y

# 安装依赖
npm install mqtt --save

After completion, we create a new index.js file in the current directory as the entry file of the project, in which to implement the complete logic of the MQTT connection test.

Node.js MQTT use

Connect to MQTT server

This article will use the free public MQTT server provided by EMQ X, which is based on the 161289b8facabc MQTT IoT cloud platform Server access information is as follows:

  • Broker: broker.emqx.io (broker-cn.emqx.io can be used in China)
  • TCP Port: 1883
  • SSL/TLS Port: 8883

Introduce the MQTT.js client library

Note: In the Node.js environment, please use the commonjs specification to import dependent modules
const mqtt = require('mqtt')

Set MQTT Broker connection parameters

Set the MQTT Broker connection address, port and topic. Here we use the function of generating random numbers in JavaScript to generate the client ID.

const host = 'broker.emqx.io'
const port = '1883'
const clientId = `mqtt_${Math.random().toString(16).slice(3)}`

Write MQTT connection function

We use the connection parameters we just set to connect, and the connected URL is spliced through the host and port ports defined above. Then call the built-in connect function of the mqtt module, and return a Client instance after the connection is successful.

const connectUrl = `mqtt://${host}:${port}`

const client = mqtt.connect(connectUrl, {
  clientId,
  clean: true,
  connectTimeout: 4000,
  username: 'emqx',
  password: 'public',
  reconnectPeriod: 1000,
})

Subscribe to topics

Use the on method of the returned Client instance to monitor the connection success status, and subscribe to the topic in the callback function after the connection is successful. At this point, we call the subscribe method of the Client instance to subscribe to the topic /nodejs/mqtt

const topic = '/nodejs/mqtt'
client.on('connect', () => {
  console.log('Connected')
  client.subscribe([topic], () => {
    console.log(`Subscribe to topic '${topic}'`)
  })
})

After subscribing to the topic successfully, we then use the on method to monitor the method of receiving the message. When the message is received, we can get the topic and message messages in the callback function of this method.

Note: The message in the callback function is of Buffer type, and you need to use the toString method to convert it to a string
client.on('message', (topic, payload) => {
  console.log('Received Message:', topic, payload.toString())
})

News release

After completing the above subscription topic and message monitoring, let's write a method for publishing messages.

Note: The message needs to be published after the MQTT connection is successful, so here we write into the callback function of Connect success
client.on('connect', () => {
  client.publish(topic, 'nodejs mqtt test', { qos: 0, retain: false }, (error) => {
    if (error) {
      console.error(error)
    }
  })
})

Complete code

The code for server connection, topic subscription, message publishing and receiving.

const mqtt = require('mqtt')

const host = 'broker.emqx.io'
const port = '1883'
const clientId = `mqtt_${Math.random().toString(16).slice(3)}`

const connectUrl = `mqtt://${host}:${port}`
const client = mqtt.connect(connectUrl, {
  clientId,
  clean: true,
  connectTimeout: 4000,
  username: 'emqx',
  password: 'public',
  reconnectPeriod: 1000,
})

const topic = '/nodejs/mqtt'
client.on('connect', () => {
  console.log('Connected')
  client.subscribe([topic], () => {
    console.log(`Subscribe to topic '${topic}'`)
  })
  client.publish(topic, 'nodejs mqtt test', { qos: 0, retain: false }, (error) => {
    if (error) {
      console.error(error)
    }
  })
})
client.on('message', (topic, payload) => {
  console.log('Received Message:', topic, payload.toString())
})

For the complete code of the project, please see: https://github.com/emqx/MQTT-Client-Examples/tree/master/mqtt-client-Node.js

test

We add a line of startup script to the script field in the package.json file.

"scripts": {
  "start": "node index.js"
}

Then you can simply use npm start to run the project.

npm start

After running, we can see the output information of the control as follows:

NodeJS MQTT 启动

We see that the client has successfully connected to the MQTT server and subscribed to the topic, received and published messages successfully. At this time, we use MQTT 5.0 client tool-MQTT X as another client for message sending and receiving tests.

MQTT 5.0 客户端工具 - MQTT X

You can see that the message sent by MQTT X is printed in the console.

控制台接收到 MQTT X 发送的消息

So far, we have completed the use of Node.js as an MQTT client to connect to the public MQTT server , and realized the connection between the test client and the MQTT server, message publishing and subscription.

Copyright statement: This article is EMQ original, please indicate the source for reprinting.

Original link: https://www.emqx.com/zh/blog/how-to-use-mqtt-in-nodejs

Technical support: If you have any questions about this article or EMQ-related products, you can visit the EMQ Q&A community https://askemq.com ask questions, and we will reply and support in time.

For more technical dry goods, please pay attention to our public account [EMQ Chinese Community].


EMQX
336 声望436 粉丝

EMQ(杭州映云科技有限公司)是一家开源物联网数据基础设施软件供应商,交付全球领先的开源 MQTT 消息服务器和流处理数据库,提供基于云原生+边缘计算技术的一站式解决方案,实现企业云边端实时数据连接、移动、...