Function node not working

I have no idea what I'm doing wrong with this function node. It's probably something really silly, but can someone help?

I'm just trying to alter a msg.payload with a simple if statement, but no matter the input the output is aways "close".

msg = {};
msg.topic = "control";

if(msg.payload == "0"){
    msg.payload = "open";
}else{
    msg.payload = "close";
}

return msg;
[{"id":"efa8eb67.7449f8","type":"debug","z":"4ffa72da.fb000c","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"payload","targetType":"msg","statusVal":"","statusType":"auto","x":1730,"y":2500,"wires":[]},{"id":"e352c18c.d678","type":"function","z":"4ffa72da.fb000c","name":"","func":"msg = {};\nmsg.topic = \"control\";\n\n\nif(msg.payload == \"0\"){\n    msg.payload = \"open\";\n}else{\n    msg.payload = \"close\";\n}\n\n\nreturn msg;","outputs":1,"noerr":0,"initialize":"","finalize":"","x":1720,"y":2440,"wires":[["5eaf9670.9d9128"]]},{"id":"5eaf9670.9d9128","type":"debug","z":"4ffa72da.fb000c","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"payload","targetType":"msg","statusVal":"","statusType":"auto","x":1890,"y":2440,"wires":[]},{"id":"40d2d495.c7a8fc","type":"inject","z":"4ffa72da.fb000c","name":"","props":[{"p":"payload"}],"repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"","payload":"1","payloadType":"str","x":1510,"y":2460,"wires":[["e352c18c.d678","efa8eb67.7449f8"]]},{"id":"94f610c2.6fba1","type":"inject","z":"4ffa72da.fb000c","name":"","props":[{"p":"payload"}],"repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"","payload":"0","payloadType":"str","x":1510,"y":2420,"wires":[["e352c18c.d678","efa8eb67.7449f8"]]}]

msg = {}; << this crates a brand new empty msg & msg.payload will ALWAYS be empty (undefined)

what happens if you delete that first line?

//msg = {};
msg.topic = "control";

if(msg.payload == "0"){
    msg.payload = "open";
}else{
    msg.payload = "close";
}

return msg;
1 Like

Ahhh of course. Thanks very much Steve, I knew it was something silly!

I was trying to clear out the msg because it had got a little messy before that node. I've rearranged now:

var result;

if(msg.payload == "0"){
    result = "open";
}else{
    result = "close";
}

msg = {};
msg.topic = "control";
msg.payload = result;

return msg;

or...

return {
  topic: "control",
  payload: msg.payload == "0" ? "open" : "close";
};
2 Likes

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