Using Functions

The function node allows arbitrary code to be run against data (messages) that are received, and then return messages that have been modified in some way to continue the flow, including splitting a message into one or more parts, performing conditional actions based on the message or other parameters, returning error messages, logging states, or any other processing that you require. Functions are the core data transformation feature of Flows, and allow complex transformation operations to be created.

Messages are passed in as a JSON object called msg. These typically have a msg.payload property that contains the body of the message.

Writing a Function

The simplest function merely returns the message unaltered, passing it on to the next nodes in the flow chain:
 

return msg;

If the function returns null, then no message is passed on, and the flow ends (any events, such as logs or error functions, must therefore occur before null is returned).

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

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

return newMsg;

Or, it can be used to return several messages:

 

var newMsg.address = "20 Enterprise, Aliso Viejo";

var newMsg.country = "USA";

return newMsg;

Or used to perform a conditional action:
 

if (newMsg.country == "USA") {

   return newMsg;

} else {

   return null;

}

Or used to log the status of the function with the log, warn or error functions:
 

node.log("An event occurred");

node.warn("Warning");

node.error("An error occurred");

For example:
 

if (newMsg.country == "USA") {
   node.log("A user correctly selected USA");

   return newMsg;

} else {

   node.error("Wrong country!");

   return null;

}

Using NPM Modules

After installing an npm package, load the module using the require() function, then use the variable to call the methods available.

For example, if you installed the mathjs module, first use the require() function to load the module into a variable (named math in this example):
 

var math = require('mathjs');

You can now use the variable into which you imported the module to call the available methods.

In the example below, the mathjs module is loaded, then the sqrt method is used to alter the contents of msg.payload:
 

var math = require('mathjs');

 

msg.payload = math.sqrt(msg.payload);     

 

return msg;