Using the Function node

The Function node allows JavaScript code to be run against the messages that are passed through it.

The message is passed in 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.

Javascript full support ECMAScript 6.0

Writing a Function

The code entered into the Function node represents the body of the function. The most simple function simply returns the message exactly as-is:

;

The returned message object does not need to be the same as was passed in; the function can construct a completely new object before returning it. For example:

msg.payload = { payload: msg.payload.length };

Working with the object msg

Accessing Payload

The msg.payload property holds the main data of the message. It can be of any data type: string, number, object, array, etc. You can access it directly or manipulate it using JavaScript functions or other nodes in your flow.

// Accessing payload
const data = msg.payload;

Setting Payload

You can set the payload of the msg object using the msg.payload property.

// Setting payload
msg.payload = "Hello, world!";

Conditional Execution

You can use the properties of the msg object to make decisions in your flow. For example, you might check the payload type or value to determine which path the flow should take.

// Conditional execution based on payload
if (msg.payload > 50) {
    // Do something
} else {
    // Do something else
}

Constructing a new message object will lose any message properties of the received message. This will break some flows, for example, the Connector node requires the msg.payload properties to be filled. In general, function nodes should return the message object they were passed after having made any changes to its properties.

Storing data context

Aside from the msg object, the function can also store data in the global variables.

More information about Global Variables within Iconnek is available here.

To set a value in a global variable:

vars.myGlobalVariable = "this is a value";

To get a value from global variables:

const myVariable = vars.myGlobalVariable

API Reference

The following objects are available within the Function node.

Node

  • msg.logs(..) : get logs from a node

  • msg.payload(..) : main body message

  • msg.params(..) : define request parameters for the following connection node

  • msg.route_params(..) : define path reference parameters for the following connector node

  • msg.query(..) : query string for the special node

Global Variables

  • vars.{variableName}(..) : set data context in variable

Dernière mise à jour