node.jsmqtt

Different `on('message')` callback per MQTT topic in Node.js


I use MQTT.js. Is it possible to define a different callback per topic?

For example, I subscribe to topics a, b, and c and create an on message callback per topic like so:

client.on('message', 'a', cb)
client.on('message', 'b', cb)
client.on('message', 'b', cb)

If not, how can I work this around?


Solution

  • No it is not possible.

    You just need to add a if/else or switch block to your on message callback that uses the topic as the selector.

    e.g.

    client.on('message', function(topic, message) {
      switch(topic) {
        case 'a':
          ...
          break;
        case 'b':
          ...
          break;
        default:
          ...
      }
    })
    

    or store callback function in an object and use topics as the key e.g.

    var callbacks = {}
    
    callbacks["a"] = function(message) {...}
    
    client.on('message', function(topic, message) {
    
      callbacks[topic](message)
    
    })