# MQTT keeps running inside a function node

**URL:** <https://discourse.nodered.org/t/mqtt-keeps-running-inside-a-function-node/22320>\
**Category:** General\
**Created:** [27 February 2020 10:50 UTC](https://discourse.nodered.org/t/mqtt-keeps-running-inside-a-function-node/22320 "2020-02-27T10:50:39Z")\
**Posts on this page:** 10\
**Page:** 1

<div class="post-metadata">

**Author:** ![Guillermo](https://avatars.discourse-cdn.com/v4/letter/g/eb8c5e/32.png) [@Guillermo](https://discourse.nodered.org/u/Guillermo)\
**Post date:** [27 February 2020 10:50 UTC](https://discourse.nodered.org/t/mqtt-keeps-running-inside-a-function-node/22320/1 "2020-02-27T10:50:39Z")

</div>

Hi all, I was trying to use the mqtt nodejs package inside a function node, so I implemented the "require" function as suggested in this comment in github:

> <https://github.com/node-red/node-red/issues/41#issuecomment-325554335>
>
> Hi. Is it possible to import/require external modules within a function node?
> Thanks!

So my code is this one:

```auto
require = global.get('require');
var mqtt = require('mqtt');

client = mqtt.connect('mqtt://test.mosquitto.org');

client.on('connect', function () {
    client.subscribe('test/test/test', function (err) {
        if (!err) client.publish('test/test/test', 'Hello mqtt');
    });
});

context.global.publish=function(msg){
    node.warn(typeof msg.payload);
    if(typeof msg.payload == "object") payload=JSON.stringify(msg.payload);
    else payload=msg.payload;
    client.publish(msg.topic,payload);
};
context.global.closeclient=function(){
    client.end();
};

client.on('message', function (topic, message) {
    // message is Buffer
    payload=message.toString();
    if(payload=="close") client.end();
    else node.warn(message.toString());
    //client.end();
});
client.on('close', function () {
    node.warn("client disconnected");
});
return null;

```

My issue here is, once I deploy again, the prior client already running keeps doing so. So when I publish on the topic "test/test/test" I get the same message times the number of times I deployed after startup (I inject everytime nodered deploys)

Could anybody help, please? Thank you in advance.

EDIT: After solving this issue, this is the function node I get

```auto
node.status({fill:"red",shape:"ring",text:"disconnected"});
require = global.get('require');
var mqtt = require('mqtt');
client = mqtt.connect('mqtt://test.mosquitto.org');

/*I made these functions in order to be able to publish messages or close the client from every function node*/
context.global.publish=function(msg){
    node.warn(typeof msg.payload);
    if(typeof msg.payload == "object") payload=JSON.stringify(msg.payload);
    else if(typeof msg.payload == "number") payload=msg.payload.toString(10);
    else payload=msg.payload;
    client.publish(msg.topic,payload);
};
context.global.closeclient=function(){
    client.end();
};

/*Client events*/
client.on('connect', function () {
    node.warn("Connected. ClientID: " + client.options.clientId);
    client.subscribe('presence', function (err) {
        if (!err){
            node.warn("subscribed to 'presence'");
            context.global.publish({topic:'presence', payload:'Hello mqtt'});
            node.status({fill:"green",shape:"dot",text:"connected"});
        }
        else node.error(err);
    });
});
client.on('message', function (topic, message) {
    // message is Buffer
    payload=message.toString();
    if(payload=="close"){
        node.warn("close");
        context.global.closeclient();
    }
    node.send({topic:topic,payload:payload});
    //client.end(); I don't want the client to end right away
});
client.on('close', function () {
    node.status({fill:"red",shape:"ring",text:"disconnected"});
    node.warn("cliente desconectado");
});

/*Node implemented in order to detect a deployment, it shuts down the client. Otherwise the client keeps subscribed and running even after a deploy*/
node.on('close', function() {
    node.warn("Deploy, closeclient");
    context.global.closeclient();
});

return null;

```

---

<div class="post-metadata">

**Author:** ![zenofmud](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/zenofmud/32/316_2.png) [@zenofmud](https://discourse.nodered.org/u/zenofmud)\
**Post date:** [27 February 2020 11:16 UTC](https://discourse.nodered.org/t/mqtt-keeps-running-inside-a-function-node/22320/2 "2020-02-27T11:16:39Z")

</div>

Can I ask why you don't use the `MQTT` nodes?

---

<div class="post-metadata">

**Author:** ![dceejay](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/dceejay/32/38_2.png) [@dceejay](https://discourse.nodered.org/u/dceejay)\
**Post date:** [27 February 2020 11:25 UTC](https://discourse.nodered.org/t/mqtt-keeps-running-inside-a-function-node/22320/3 "2020-02-27T11:25:41Z")

</div>

in your close function you are just saying disconnected... you aren't actually disconnecting.

---

<div class="post-metadata">

**Author:** ![Guillermo](https://avatars.discourse-cdn.com/v4/letter/g/eb8c5e/32.png) [@Guillermo](https://discourse.nodered.org/u/Guillermo)\
**Post date:** [27 February 2020 11:38 UTC](https://discourse.nodered.org/t/mqtt-keeps-running-inside-a-function-node/22320/4 "2020-02-27T11:38:44Z")

</div>

Sure, that is because I would like to dynamically change the ID of the MQTT client

---

<div class="post-metadata">

**Author:** ![Guillermo](https://avatars.discourse-cdn.com/v4/letter/g/eb8c5e/32.png) [@Guillermo](https://discourse.nodered.org/u/Guillermo)\
**Post date:** [27 February 2020 11:40 UTC](https://discourse.nodered.org/t/mqtt-keeps-running-inside-a-function-node/22320/5 "2020-02-27T11:40:13Z")

</div>

Yeah, I copypasted while trying different things and forgot to uncomment that part in particular. But the issue here is how to close the client once I deploy again

Edit: Sorry, I misunderstood the message. Anyway on the event "close" the client is already closing, there is no need to close it again. That part is only for when the client is already closed, it only shows "I am disconnected"

---

<div class="post-metadata">

**Author:** ![knolleary](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/knolleary/32/3_2.png) [@knolleary](https://discourse.nodered.org/u/knolleary)\
**Post date:** [27 February 2020 11:41 UTC](https://discourse.nodered.org/t/mqtt-keeps-running-inside-a-function-node/22320/6 "2020-02-27T11:41:26Z")

</div>

You need to add a handler on the 'close' event of the `node` object as described here: [https://nodered.org/docs/user-guide/writing-functions#tidying-up](https://nodered.org/docs/user-guide/writing-functions#tidying-up)

---

<div class="post-metadata">

**Author:** ![Guillermo](https://avatars.discourse-cdn.com/v4/letter/g/eb8c5e/32.png) [@Guillermo](https://discourse.nodered.org/u/Guillermo)\
**Post date:** [27 February 2020 15:27 UTC](https://discourse.nodered.org/t/mqtt-keeps-running-inside-a-function-node/22320/7 "2020-02-27T15:27:46Z")

</div>

Thank you very much, this was exactly the thing I was looking for! 🙂

---

<div class="post-metadata">

**Author:** ![cymplecy](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/cymplecy/32/2773_2.png) [@cymplecy](https://discourse.nodered.org/u/cymplecy)\
**Post date:** [27 February 2020 16:46 UTC](https://discourse.nodered.org/t/mqtt-keeps-running-inside-a-function-node/22320/8 "2020-02-27T16:46:55Z")

</div>

Could you publish your function node when you get it working as I think a few people are interested in ability to dynamically change MQTT connections

---

<div class="post-metadata">

**Author:** ![Guillermo](https://avatars.discourse-cdn.com/v4/letter/g/eb8c5e/32.png) [@Guillermo](https://discourse.nodered.org/u/Guillermo)\
**Post date:** [28 February 2020 10:14 UTC](https://discourse.nodered.org/t/mqtt-keeps-running-inside-a-function-node/22320/9 "2020-02-28T10:14:57Z")

</div>

Sure, the function node is after the "EDIT" in the OP

---

<div class="post-metadata">

**Author:** ![system](https://us1.discourse-cdn.com/flex026/uploads/nodered/original/1X/d073cd938eafa2e558d7c2cd59003b3ef4963033.png) [@system](https://discourse.nodered.org/u/system)\
**Post date:** [13 March 2020 10:14 UTC](https://discourse.nodered.org/t/mqtt-keeps-running-inside-a-function-node/22320/10 "2020-03-13T10:14:57Z")

</div>

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.
