Writing Functions Guide
A function component runs JavaScript code on the incoming message and passes it on.
If you are planning to use the function again in other projects, you can create a specific component instead. Learn creating a new component (and functions writing in .js file of its project) in New Component Creation Tutorial.
By convention, an incoming message is an object called msg, and the body of this message contained in the msg.payload property.
Other components may attach other properties to msg. Check their documentation when using.

Writing a Function

For your convenience, you may open a wider editor field for a function component:

Basics

    The default body of a function is return msg; that passes the incoming message without changes.
    If the function returns null there will be no outcoming message and the flow ends.
    The function doesn't have to return the same message object. It can construct a completely new object. For example:
1
var newMsg = { payload: msg.payload.length };
2
return newMsg;
Copied!
Note: a new message in this instance will lose all the properties of the incoming message. So in many situations, the function should keep the incoming message object when updating its properties. For example, the HTTP In/Response flow requires the msg.req and msg.res properties to be preserved end-to-end.
    For debuggging purposes use node.warn() that shows warnings in the sidebar. For example:
1
node.warn("my var xyz = " + xyz);
Copied!
See Logging events for more details.

Multiple Outputs

The function component can have multiple outputs. For example, all the messages with "simon" msg.topic will go to the second output here:
1
if (msg.topic === "simon") {
2
return [ null, msg ];
3
} else {
4
return [ msg, null ];
5
}
Copied!
The following function will return the incoming message without changes to the first output and its payload length to the second one:
1
var newMsg = { payload: msg.payload.length };
2
return [msg, newMsg];
Copied!
The number of outputs points are set up in the bottom property:

Multiple Messages

If one of returning messages will be also an array, the corresponding output will show multiple messages.
1
var msg1 = { payload:"output 1, message 1" };
2
var msg2 = { payload:"output 1, message 2" };
3
var msg3 = { payload:"output 1, message 3" };
4
var msg4 = { payload:"output 2" };
5
return [ [ msg1, msg2, msg3 ], msg4 ];
Copied!
In the next example, the function converts the input string to an array of words and returns them as multiple messages.
1
var multiMsg = [];
2
var words = msg.payload.split(" ");
3
for (var word in words) {
4
multiMsg.push({payload:words[word]});
5
}
6
return [ multiMsg ];
Copied!

Sending messages asynchronously

Use a node.send() function to send messages immediately.
An asynchronous action function before sending a message.
1
someAsynchAction(msg, function(result) {
2
msg.payload = result;
3
node.send(msg);
4
});
5
return;
Copied!
The function component will clone every message object you pass to node.send to ensure there is no unintended modification of message objects that get reused in the function.
The function can forbid the runtime to clone the first message passed to node.send by passing in false as a second argument to the function. It would do this if the message contains something that is not otherwise cloneable, or for performance reasons to minimize the overhead of sending messages:
1
node.send(msg,false);
Copied!

Finishing with the message

To signal the runtime that asynchronous message handling is finished the function should call node.done(). And the runtime will properly track messages through the system.

Running code on start

In a Setup tab, you can provide code that will run when the component is started.
For example, you can initialize values in a local context that the main function will use:
1
if (context.get("currentLevel") === undefined) {
2
context.set("currentLevel", 100)
3
}
Copied!
The Setup function can return a Promise if it needs to complete asynchronous work before the main Function can start processing messages. Any messages that arrive before the Setup function has completed will be queued up, and handled when it is ready.

Tidying up

You can tidy up any outstanding requests and close any connection on flow redeployment in two ways:
    add a close event handler:
1
node.on('close', function() {
2
// tidy up any async code here - shutdown connections and so on.
3
});
Copied!
    or add code to the Close tab in the edit dialog.

Logging events

If you want the component to log some information to console use these functions:
1
node.log("Something going on");
2
node.warn("Pay attantion to this");
3
node.error("There is a problem");
4
//and additionally:
5
node.trace("Log some internal detail not needed for normal operation");
6
node.debug("Log something more details for debugging the component's behaviour");
Copied!
The warn and error messages also get sent to the flow editor debug tab.

Handling errors

When the function encounters it returns nothing, but a catch component can log the problem. See the catch component description.
A catch component can be triggered when the function calls node.error() with the original message as a second argument:
1
node.error("there is an error", msg);
Copied!

Storing data

Beside the msg object, the function can store data in the context store.
There are three predefined variables to access context:
    context: the component's local context
    flow: the flow context, the variable value is available for other components in the flow
    global: the value is accessible in the global (all flows) scope
Note: these variables are the function component way to deal with context. In custom components, it's done differently.
A function can access context in common or asynchronous mode. 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.
Getting a value:
1
var getCount = flow.get("count");
Copied!
Setting a value:
1
flow.set("count", 111);
Copied!
For example, here the function counts how many times it has been run:
1
// create the counter = 0 if it doesn't exist, or get the value from context
2
var count = context.get('count')||0;
3
count += 1;
4
// store the value back to context
5
context.set('count',count);
6
// attach it to the output msg object
7
msg.count = count;
8
return msg;
Copied!

Get and Set multiple values

The rule is the same as with multiple outputs: use an array.
1
var values = flow.get(["count", "colour", "length"]);
2
...
3
flow.set(["count", "colour", "temperature"], [123, "red"]);
Copied!
Note that in this instance length will be set to null due to missing value.

Asynchronous context access

Use an extra callback parameter for the get and set functions to access the context store asynchronously.
1
// Get single value
2
flow.get("count", function(err, getCount) { ... });
3
​
4
// Get multiple values
5
flow.get(["count", "colour"], function(err, count, colour) { ... })
6
​
7
// Set single value
8
flow.set("count", 123, function(err) { ... })
9
​
10
// Set multiple values
11
flow.set(["count", "colour", [123, "red"], function(err) { ... })
Copied!
The first argument passed to the callback, err, is only set if an error occurred when accessing context.
The asynchronous version of the count example becomes:
1
context.get('count', function(err, count) {
2
if (err) {
3
node.error(err, msg);
4
} else {
5
// initialise the counter to 0 if it doesn't exist already
6
count = count || 0;
7
count += 1;
8
// store the value back
9
context.set('count',count, function(err) {
10
if (err) {
11
node.error(err, msg);
12
} else {
13
// make it part of the outgoing msg object
14
msg.count = count;
15
// send the message
16
node.send(msg);
17
}
18
});
19
}
20
});
Copied!

Multiple context stores

A function can configure multiple context stores. For example, both a memory and file based store could be used.
To identify the store to use add an optional parameter to the get/set context functions.
1
// Get value - sync
2
var functionCount = flow.get("count", storeName);
3
​
4
// Get value - async
5
flow.get("count", storeName, function(err, functionCount) { ... });
6
​
7
// Set value - sync
8
flow.set("count", 111, storeName);
9
​
10
// Set value - async
11
flow.set("count", 111, storeName, function(err) { ... })
Copied!

Global context

The global context can be pre-populated with objects when Apps Editor starts. This is defined in the main settings.js file under the functionGlobalContext property.
For example, learn how to Load additional modules within the function component using global context.

Adding status

You can add status markers to the function component by calling special functions:
1
node.status({fill:"red",shape:"ring",text:"disconnected"});
2
node.status({fill:"green",shape:"dot",text:"connected"});
3
node.status({text:"text status"});
4
node.status({}); // clears the status
Copied!
See how it's done in custom components. The parameters and the result are the same.

Load additional modules

To use additional modules within the function component they must be loaded in global context. The module must be loaded to the main settings.js file and added to the functionGlobalContext property.
1
functionGlobalContext: {
2
externalModule:require('external')
3
}
Copied!
at which point, the module can be referenced within a function as global.get('externalModule').
Modules loaded from your settings file must be installed in the same directory as the settings file. To do this open the project terminal and run:
1
npm install name_of_external_module
Copied!

API Reference

The following objects are available within the Function node.

node

context

    context.get(..) : get a component-scoped context property
    context.set(..) : set a component-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

APPS

    APPS.util.cloneMessage(..) : safely clones a message object so it can be reused

env

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

Other modules and functions

The function component 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.
Note: the function component automatically clears any outstanding timeouts or interval timers whenever it is stopped or re-deployed.
Last modified 6mo ago