'Using function with moonnode (moonraker api) in nodered

I'm using Moonnode for the Moonraker API (3d printer) this node outputs several values. I want to use some values to control a neopixel LED.

the output looks like this

debug output

the path looks like this:

payload.fullModel.print_stats.state

I've created a function to listen to the printing status. but it does not work, so i probably did something wrong :)

var obj = { payload: payload.fullModel.print_stats };

var matrisculeString =obj["state"]; 

return msg;

in the debug I see this output

ReferenceError: payload is not defined (line 1, col 22)

Can anybody help me?



Solution 1:[1]

A couple of things, everything arriving into the Node-RED Function node is relative to the msg object

So the error is because your first line should look something like:

var obj = { payload: msg.payload.fullModel.print_stats };

That being said the rest of the function isn't actually doing anything useful.

var matrisculeString =obj["state"]; 

This is going to fail because there is no state field in the obj object (You've just created it the line before and the only field it has is payload)

If also looks like obj may be intended to be the msg object you later send onward (even though you don't actually use it and just return the original input msg object). It is considered bad form to create new objects rather than reuse the input object because this leads to it loosing all the field and data that might be attached to the input object that may be needed further down the flow e.g. the HTTP-response object must receive as input an object that starts at the HTTP-in node because it contains all the required input to send a reply to the HTTP client that made the request that started the flow.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 hardillb