Building Simple Applications with Node.js and MQTT

  ·   3 min read

In the evolving world of Internet of Things (IoT) and real-time applications, MQTT (Message Queuing Telemetry Transport) has emerged as a lightweight messaging protocol that’s perfect for small sensors and mobile devices. In this article, we’ll explore how to develop simple Node.js applications that communicate through an MQTT broker. This will give you a basic understanding of both MQTT and Node.js while allowing you to set up a simple messaging system between two applications.

Prerequisites

Before we dive in, ensure that you have the following prerequisites:

Step 1: Setting Up the MQTT Broker

If you are using a local MQTT broker like Mosquitto, you can install it via your package manager. For example, on Ubuntu:

sudo apt-get update
sudo apt-get install mosquitto mosquitto-clients

After installing, start the Mosquitto service:

sudo systemctl start mosquitto

You can verify that the broker is running using the following command:

systemctl status mosquitto

For cloud-based options, you can sign up for a free account at a service like HiveMQ or Cloud MQTT.

Step 2: Installing the Required Node.js Packages

Next, we need to set up our Node.js applications. Create a new directory for your project, and run the following commands:

mkdir mqtt-apps
cd mqtt-apps
npm init -y
npm install mqtt

This will create a new Node.js project and install the mqtt package that allows you to connect to an MQTT broker.

Step 3: Creating the Publisher Application

Now, let’s create a simple publisher application that will send messages to the broker. Create a file named publisher.js and add the following code:

const mqtt = require('mqtt');

// Replace with your MQTT broker URL
const brokerUrl = 'mqtt://localhost'; // For cloud, use your broker URL
const client = mqtt.connect(brokerUrl);

client.on('connect', () => {
    console.log('Publisher connected to MQTT broker');
    
    // Publish a message every 5 seconds
    setInterval(() => {
        const message = `Hello MQTT at ${new Date()}`;
        client.publish('test/topic', message, { qos: 1 });
        console.log(`Message published: ${message}`);
    }, 5000);
});

Explanation

  • Connection: Connects to the MQTT broker.
  • Publishing: Publishes a message to the test/topic every 5 seconds.

Step 4: Creating the Subscriber Application

Next, we will create a subscriber application that listens to incoming messages. Create a file named subscriber.js and add the following code:

const mqtt = require('mqtt');

// Replace with your MQTT broker URL
const brokerUrl = 'mqtt://localhost'; // For cloud, use your broker URL
const client = mqtt.connect(brokerUrl);

client.on('connect', () => {
    console.log('Subscriber connected to MQTT broker');
    
    // Subscribe to the topic
    client.subscribe('test/topic', { qos: 1 }, (err) => {
        if (!err) {
            console.log('Subscribed to test/topic');
        }
    });
});

// Handle incoming messages
client.on('message', (topic, message) => {
    console.log(`Message received from ${topic}: ${message.toString()}`);
});

Explanation

  • Subscription: The subscriber connects and subscribes to the test/topic.
  • Message Handling: Logs any messages that are received.

Step 5: Running Your Applications

Open two terminal windows. In the first terminal, run the publisher:

node publisher.js

In the second terminal, run the subscriber:

node subscriber.js

You should see the subscriber logging messages that the publisher sends every 5 seconds.

Conclusion

You’ve just created a basic messaging system using Node.js and MQTT! This foundational setup can be expanded into more complex applications such as IoT systems, chat applications, and more. The MQTT protocol is perfect for applications that require low bandwidth and real-time communication.

Additional Resources

Using open-source tools like Node.js and Mosquitto, you can build efficient communication systems capable of scaling as your application grows. Enjoy building your next Node.js project with MQTT!