Function
Executes a custom Javascript function in the flow context. The function should always return a message object or an array of message objects.
How It Works
- The node creates an isolated V8 JavaScript runtime environment
- Local variables are initialized with their default values based on type
- The JavaScript function is wrapped with helper utilities (
local,global,flow,console) - The current message object is passed as the
msgparameter to your function - Your custom JavaScript code executes within the configured timeout period
- The function must return either:
- A single message object (for single output)
- An array of message objects or nulls (for multiple outputs)
- The returned message(s) are packaged and sent to the corresponding output port(s)
- If the script exceeds the timeout, execution is terminated with an error
- The V8 runtime is disposed after execution completes
Requirements
- The function must return a valid message object or array of message objects
- For multiple outputs, return an array with length matching the "Outputs" configuration
- Use
nullin the output array for ports that should not receive data - Global/Flow variables must exist before being accessed via
global.get()orflow.get() - Local variables must be defined in the "Local Variables" section before use
- Script must complete within the configured timeout (default: 30 seconds)
Error Handling
| Error Code | Description | Cause |
|---|---|---|
Core.Programming.Function.ErrOnCreate (Config parse) | Config parse error | Invalid node configuration during creation |
Core.Programming.Function.ErrOnCreate (JS VM) | JS VM create error | Failed to initialize V8 JavaScript engine |
Core.Programming.Function.OnMessage | Message parse error | Invalid message format received |
Core.Programming.Function.ErrV8Context | V8 context error | Failed to create JavaScript execution context |
Core.Programming.Function.ErrTimeout | Script timeout | Script execution exceeded the configured timeout |
Core.Programming.Function.ErrJSScriptError at [location] | JavaScript error | Your JavaScript code threw an exception or has syntax errors |
Core.Programming.Function.ErrPackageMsg | Message packaging error | Failed to package the returned message |
Core.Programming.Function.ErrMsg | No message returned | Function did not return any message object |
Common Properties
- Name - The custom name of the node.
- Color - The custom color of the node.
- Delay Before (sec) - Waits in seconds before executing the node.
- Delay After (sec) - Waits in seconds after executing node.
- Continue On Error - Automation will continue regardless of any error. The default value is false.
if ContinueOnError property is true, no error is caught when the project is executed even if Catch node is used.
Options
- Function - Custom JavaScript function to execute.
- Outputs - Number of expected outputs from the function.
- Script Timeout - Maximum time in seconds before the script times out (default: 30 seconds).
Local Variables
Defines local variables which can be used in the function. Local variables are scoped to this Function node only and persist across executions within the same flow run.
JavaScript API Reference
Message Object (msg)
msg- The current message object passed from the previous node- Access properties:
msg.fieldNameormsg["field-name"] - Modify properties:
msg.newField = value
Local Variables API
local.get(variableName)- Get a local variable valuelocal.set(variableName, value)- Set a local variable valuelocal.lock()- Acquire mutex lock for thread-safe accesslocal.unlock()- Release mutex lock
Global Variables API
global.get(variableName)- Get a global variable valueglobal.set(variableName, value)- Set a global variable valueglobal.lock()- Acquire mutex lock for thread-safe accessglobal.unlock()- Release mutex lock
Flow Variables API
flow.get(variableName)- Get a flow variable valueflow.set(variableName, value)- Set a flow variable valueflow.lock()- Acquire mutex lock for thread-safe accessflow.unlock()- Release mutex lock
Console API
console.log(...)- Print values to system console (supports multiple arguments)
Usage Examples
Example 1: Simple Data Transformation
// Convert temperature from Celsius to Fahrenheit
msg.fahrenheit = (msg.celsius * 9/5) + 32;
msg.unit = "F";
return msg;
Transform message data by adding calculated fields.
Example 2: Conditional Routing (Multiple Outputs)
// Route messages based on order total
if (msg.orderTotal > 1000) {
// High-value orders go to output 1
msg.category = "Premium";
return [msg, null];
} else {
// Regular orders go to output 2
msg.category = "Standard";
return [null, msg];
}
Route to different ports based on business logic.
Example 3: Using Global Variables
// Increment global counter and add to message
let count = global.get("processedOrders") || 0;
count++;
global.set("processedOrders", count);
msg.orderNumber = count;
msg.timestamp = new Date().toISOString();
return msg;
Track state across multiple flow executions using global variables.
Example 4: Working with Local Variables
// Use local variable as a buffer
let buffer = local.get("dataBuffer") || [];
buffer.push(msg.record);
if (buffer.length >= 10) {
// Send batch and clear buffer
msg.batch = buffer;
local.set("dataBuffer", []);
return msg;
} else {
// Not enough records yet, update buffer
local.set("dataBuffer", buffer);
return null; // Don't send message yet
}
Accumulate data in local variables for batch processing.
Example 5: Array Processing
// Filter and transform an array
if (msg.users && Array.isArray(msg.users)) {
msg.activeUsers = msg.users
.filter(user => user.status === "active")
.map(user => ({
id: user.id,
name: user.firstName + " " + user.lastName,
email: user.email
}));
}
return msg;
Process arrays using standard JavaScript methods.
Example
Return example of a single output Function node.
msg.count = 0;
return msg;
Return example of a multiple output Function node.
if (msg.price > 50) {
return [msg, null];
} else {
return [null, msg];
}
Usage Notes
- The Function node uses V8 JavaScript engine (same as Chrome/Node.js)
- All standard JavaScript features are available (ES6+, async not supported)
- Variables accessed via
local,global, andflowAPIs are automatically serialized to JSON - Returning
nullfor single output will still generate an error - return the msg object instead - For multiple outputs, use
nullin array positions where no message should be sent - The script timeout cannot be disabled - always configure an appropriate timeout value
- Large objects or complex computations may impact performance - consider timeout accordingly
- Use
console.log()for debugging - output appears in system console during development - Local variables persist only within the same flow execution, not across different runs
Tips
- Keep functions focused - complex logic is better split across multiple Function nodes
- Use meaningful local variable names to make code maintainable
- Add comments to complex JavaScript logic for future reference
- Test timeout values with representative data volumes to avoid unexpected failures
- Use mutex locks (
local.lock()/unlock()) when modifying shared variables in parallel flows - Leverage multiple outputs for branching logic instead of multiple Switch nodes
- Initialize variables with sensible defaults:
let value = msg.field || defaultValue - Use
try/catchwithin your function for graceful error handling - For intensive calculations, increase the Script Timeout to prevent premature termination