Skip to content

Instantly share code, notes, and snippets.

@ddewaele
Created October 7, 2023 18:27
Show Gist options
  • Save ddewaele/aaeb174394b46402f64f3d2bc8d5f0c3 to your computer and use it in GitHub Desktop.
Save ddewaele/aaeb174394b46402f64f3d2bc8d5f0c3 to your computer and use it in GitHub Desktop.

Revisions

  1. ddewaele created this gist Oct 7, 2023.
    41 changes: 41 additions & 0 deletions index.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,41 @@
    const mqtt = require('mqtt');
    const fs = require('fs');

    // Source broker details
    const sourceBrokerUrl = "mqtts://somebroker.com";
    const sourceOptions = {
    port: 8883,
    ca: [fs.readFileSync('/home/ubuntu/keys/server/server.crt')],
    key: fs.readFileSync('/home/ubuntu/keys/client.key'),
    cert: fs.readFileSync('/home/ubuntu/keys/client.crt'),
    rejectUnauthorized: true
    };

    // Destination broker details
    const destBrokerUrl = "mqtt://localhost:1883";

    const sourceClient = mqtt.connect(sourceBrokerUrl, sourceOptions);
    const destClient = mqtt.connect(destBrokerUrl);

    sourceClient.on('connect', () => {
    console.log('Connected to source broker');
    sourceClient.subscribe('topic/of/interest/#');
    });

    sourceClient.on('message', (topic, message) => {
    console.log(`Received message on topic '${topic}': ${message.toString()}`);
    destClient.publish(topic, message);
    });

    destClient.on('connect', () => {
    console.log('Connected to destination broker');
    });

    // Handle errors (optional but recommended)
    sourceClient.on('error', (err) => {
    console.error('Source broker error:', err);
    });

    destClient.on('error', (err) => {
    console.error('Destination broker error:', err);
    });