Using a JavaScript
In the Automation Studio, you can execute your own javascript functions using the 'function' nodes. If you are familiar with this javascript function, you can manipulate the property directly.
The message is passed on as an object called 'msg'. By convention, it will have a 'msg.payload' property containing the body of the message. Other nodes may attach their own properties to the message, and they should be described in their documentation.
Writing a Function
The code entered into the Function node represents the body of the function. If the function returns null, then no message is passed on and the flow ends. The function must always return a msg object. Returning a number or string will result in an error.
Example
The 'Function' node routes a message based on the timestamp seconds. Odd numbered seconds message goes to port 1 and even numbered seconds message goes to port 2.
Logging events
If a node needs to log something to the console, it can use one of the following functions:
node.log("Something happened");
node.warn("Something happened you should know about");
node.error("Oh no, something bad happened");
The warn and error messages also get sent to the flow editor debug tab.
Storing data
Aside from the msg object, the function node can also store data into the context store.
In the Function node there are three predefined variables that can be used to access the context:
- context - the nodes local context
- flow - flow scope context
- global - global scope context
API Reference
Further reference: https://nodered.org/docs/user-guide/writing-functions#api-reference
- node
- node.id : the ID of the Function node - added in 0.19
- node.name : the name of the Function node - added in 0.19
- node.log(..) : log a message
- node.warn(..) : log a warning message
- node.error(..) : log an error message
- node.debug(..) : log a debug message
- node.trace(..) : log a trace message
- node.on(..) : register an event handler
- node.status(..) : update the node status
- node.send(..) : send a message
- context
- context.get(..) : get a node-scoped context property
- context.set(..) : set a node-scoped context property
- context.keys(..) : returns a list of all node-scoped context property keys
- context.flow : same as flow
- context.global : same as global
- flow
- flow.get(..) : gets a flow-scoped context property
- flow.set(..) : set a flow-scoped context property
- flow.keys(..) : returns a list of all flow-scoped context property keys
- global
- global.get(..) : get a global-scoped context property
- global.set(..) : set a global-scoped context property
- global.keys(..) : return a list of all global-scoped context property keys
For node-red function nodes, go to the user guide : https://nodered.org/docs/user-guide/writing-functions