Skip to end of metadata
Go to start of metadata

You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 3 Next »

The Function node uses JavaScript code construct your logic for the flow.

The message is passed in as an object named msg. In general, the body of the message is present in the payload property msg.payload of the msg object. The other nodes may attach their own properties to the message object.

Function editor

You can enter custom code into the Function node and add return msg; at the end to return the whole msg to be passed on to the next node in the flow.

The function must always return a msg object.

If the function returns null, then no message is passed on through the function node.

Returning a number or string will result in an error.

Though it is not advised to rewrite the whole message object, you can construct a completely new object before returning it. For example:

var newMsg = { payload: msg.payload.length };
return newMsg;

Constructing a new message object will lose any message properties of the received message. This will break some flows, for example, the HTTP In/Response flow requires the msg.req and msg.res properties to be preserved end-to-end.

You can click on the expand button to expand the code editor to fill the screen.

In the expanded mode, click on the Cancel button to return to the windowed mode.

Use node.warn() to show warnings in the sidebar to help you debug. For example:

node.warn("my var xyz = " + xyz);

See the logging section below for more details.

Multiple Outputs

If there is more than one output, an array of messages can be returned by the function to send to the outputs. You can increase the number of outputs (also the pins of the function node) by changing the Outputs number (highlighted in the screenshot below).

In the Experience Designer, the function node with 3 outputs:

This makes it easy to write a function that sends the message to different outputs depending on some conditions. For example, this function would send anything on the topic banana to the second output rather than the first:

if (msg.topic === "banana") {
   return [ null, msg ];
} else {
   return [ msg, null ];
}

The following example passes the original message as-is on the first output and a message containing the payload length is passed to the second output:

var newMsg = { payload: msg.payload.length };
return [msg, newMsg];

Multiple Messages

A function can return multiple messages on the output by returning an array of messages within the returned array. When multiple messages are returned for an output, subsequent nodes will receive the messages one at a time in the order they were returned.

In the following example, msg1msg2msg3 will be sent to the first output. msg4 will be sent to the second output.

var msg1 = { payload:"first out of output 1" };
var msg2 = { payload:"second out of output 1" };
var msg3 = { payload:"third out of output 1" };
var msg4 = { payload:"only message from output 2" };
return [ [ msg1, msg2, msg3 ], msg4 ];

The following example splits the received payload into individual words and returns a message for each of the words.

var outputMsgs = [];
var words = msg.payload.split(" ");
for (var w in words) {
    outputMsgs.push({payload:words[w]});
}
return [ outputMsgs ];

Event logs

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 debug tab on the right side of the Experience Designer.

For finer-grained logging, node.trace() and node.debug() are also available. If there is no logger configured to capture those levels, they will not be seen.

Error Handling

If the function encounters an error that should halt the current flow, it should return nothing. To trigger a Catch node on the same tab, the function should call node.error with the original message as a second argument:

node.error("hit an error", msg);

Storing data

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

In the Function node there are three predefined variables that can be used to access context:

  • context - the node’s local context

  • flow - the flow scope context

  • global - the global scope context

The following examples use flow context but apply equally well to context and global.

There are two modes for accessing context; either synchronous or asynchronous. The built-in context stores provide both modes. Some stores may only provide asynchronous access and will throw an error if they are accessed synchronously.

To get a value from context:

var myCount = flow.get("count");

To set a value:

flow.set("count", 123);

The following example maintains a count of how many times the function has been run:

// initialise the counter to 0 if it doesn't exist already
var count = context.get('count')||0;
count += 1;
// store the value back
context.set('count',count);
// make it part of the outgoing msg object
msg.count = count;
return msg;

Get/Set multiple values

It is also possible to get or set multiple values in one go:

Get

var values = flow.get(["count", "colour", "temperature"]);
// values[0] is the 'count' value
// values[1] is the 'colour' value
// values[2] is the 'temperature' value

Set

flow.set(["count", "colour", "temperature"], [123, "red", "12.5"]);

In this case, any missing values are set to null.

Status

The function node can also provide its own status decoration in the same way that other nodes can. To set the status, call the node.status function. For example

node.status({fill:"red",shape:"ring",text:"disconnected"});
node.status({fill:"green",shape:"dot",text:"connected"});
node.status({text:"Just text status"});

The shape property can be: ring or dot.

The fill property can be: redgreenyellowblue or grey

If the status object is an empty object, {}, then the status entry is cleared from the node.

node.status({});   // to clear the status

Any status updates can then also be caught by the Status node.

Additional modules

Additional node modules cannot be loaded directly within a Function node. Refer, What external libraries and modules are allowed in Experience Designer? for supported modules and libraries.

API Reference

The following objects are available within the Function node.

node

  • node.id : the id of the Function node

  • node.name : the name of the Function node

  • 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

  • node.done(..) : finish with a message

context

  • context.get(..) : get a node-scoped context property

  • context.set(..) : set a node-scoped context property

  • context.keys(..) : return a list of all node-scoped context property keys

  • context.flow : same as flow

  • context.global : same as global

flow

  • flow.get(..) : get a flow-scoped context property

  • flow.set(..) : set a flow-scoped context property

  • flow.keys(..) : return 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

env

  • env.get(..) : get an environment variable

Other modules and functions

The Function node also makes the following modules and functions available:

  • Buffer - the Node.js Buffer module

  • console - the Node.js console module (node.log is the preferred method of logging)

  • util - the Node.js util module

  • setTimeout/clearTimeout - the javascript timeout functions.

  • setInterval/clearInterval - the javascript interval functions.

The function node automatically clears any outstanding timeouts or interval timers whenever it is stopped or re-deployed.

For more information on the Function node, please refer to Function node documentation.

Related Articles

  • No labels