# Connect to the Deployment with Node.js
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.
Node.js (opens new window) is a JavaScript runtime built on Chrome's V8 JavaScript engine. Before the emergence of Node.js, JavaScript was usually used as a client-side programming language, and the programs are written in JavaScript often ran on the user's browser. The appearance of node.js enables JavaScript to be used for server-side programming.
MQTT (opens new window) 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 industries such as the IoT, mobile Internet, smart hardware, Internet of Vehicles and power energy.
# Preconditions
- The deployment has been created. You can view connection-related information under Deployment Overview. Please make sure that the deployment status is running. At the same time, you can use WebSocket to test the connection to the MQTT server.
- Set the user name and password in
Authentication & ACL
>Authentication
for connection verification.
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
2
3
# Install dependencies
MQTT.js (opens new window) 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 (opens new window) in the JavaScript ecosystem.
# create a new project
npm init -y
# Install dependencies
npm install mqtt --save
2
3
4
5
After the installation, we create a new index.js file in the current directory as the entry file of the project, in which we can implement the complete logic of the MQTT connection test.
# Connection
Please find the relevant address and port information in the Deployment Overview of the Console. Please note that if it is the basic edition, the port is not 1883 or 8883, please confirm the port.
# Connection settings
This article will use Free Public MQTT Server (opens new window) provided by EMQX, which is created based on EMQX's MQTT IoT Cloud Platform (opens new window). The server access information is as follows:
- Broker: broker.emqx.io
- TCP Port: 1883
- SSL/TLS Port: 8883
Import the MQTT.js client library
Note: In the Node.js environment, please use the commonjs specification to import dependency 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)}`;
2
3
# Write MQTT connect function
We use the connection parameters just set to connect, and the URL for the connection is spliced through the host and port ports defined above. Then, we call the built-in connect function of the MQTT module, and it will 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,
});
2
3
4
5
6
7
8
9
10
# Subscribe to topics
We use the on function of the returned Client instance to monitor the connection status, and subscribe to the topic in the callback function after the connection is successful. At this point, we call the subscribe function of the Client instance to subscribe to the topic /nodejs/mqtt
after the connection is successful.
const topic = "/nodejs/mqtt";
client.on("connect", () => {
console.log("Connected");
client.subscribe([topic], () => {
console.log(`Subscribe to topic '${topic}'`);
});
});
2
3
4
5
6
7
After subscribing to the topic successfully, we then use the on function to monitor the function of receiving the message. When the message is received, we can get the topic and message in the callback function of this function.
Note: The message in the callback function is of Buffer type and needs to be converted into a string by the toString function
client.on("message", (topic, payload) => {
console.log("Received Message:", topic, payload.toString());
});
2
3
# Publish messages
After completing the above topic subscription and message monitoring, we will write a function for publishing messages.
Note: The message needs to be published after the MQTT connection is successful, so we write it in the callback function after the connection is successful
client.on("connect", () => {
client.publish(
topic,
"nodejs mqtt test",
{ qos: 0, retain: false },
(error) => {
if (error) {
console.error(error);
}
}
);
});
2
3
4
5
6
7
8
9
10
11
12
# 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());
});
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
For the complete code of the project, please see: https://github.com/emqx/MQTT-Client-Examples/tree/master/mqtt-client-Node.js (opens new window).
# Test
We add a line of startup script to the script field in the package.json file.
"scripts": {
"start": "node index.js"
}
2
3
Then we can simply use npm start
to run the project.
npm start
After running, we can see the output information of the console as follows:
We see that the client has successfully connected to the MQTT broker (opens new window) and subscribed to the topic, received and published messages successfully. At this point, we will use MQTT 5.0 Client Tool - MQTT X (opens new window) as another client for the message publishing and receiving test.
We can see that the message sent by MQTT X is printed in the console.
# More
So far, we have used Node.js as an MQTT client to connect to the public MQTT broker (opens new window), and realizes the connection, message publishing and subscription between the test client and MQTT server. You can download the source code of the example here (opens new window), and you can also find more demo examples in other languages on GitHub (opens new window).