MQTT in NodeJS application

Author
April 06, 2022

In this article i will explain you how you can work with MQTT in NodeJS application

Step 1: Install MQTT package

npm install mqtt --save

Step 2: Add the following code to your Nodejs application

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

client.on("connect", function () {
  client.subscribe("presence", function (err) {
    if (!err) {
      client.publish("presence", "Hello mqtt");
    }
  });
});

client.on("message", function (topic, message) {
  // message is Buffer
  console.log(message.toString());
  client.end();
});

-In this code we are connecting with IOT application and subscribing and publishing to the topic

In MQTT we generally communicate with IOT application using topic where application publish message to the topic and other application who have subscribed to this topic get the message

client.on("connect", function () {
  client.subscribe("presence", function (err) {
    if (!err) {
      client.publish("presence", "Hello mqtt");
    }
  });
});
  • Getting message from the topic

This is the code where we get message from the topic

client.on("message", function (topic, message) {
  // message is Buffer
  console.log(message.toString());
  client.end();
});