JavaScript Node

The JavaScript Node executes any valid JavaScript code as a function and can return any valid JavaScript object as a return value. The function can also update any of its arguments by reference, including public variables. The JavaScript Node supportNodeJS version 10.

Xponent uses the Node JavaScript engine to execute the JavaScript functions. The full Node library is available with a few notable exceptions for security reasons which includes the http, os and fs modules. Any valid Node JavaScript can be executed within the function - including other embedded functions. The Script Editor uses JavaScript syntax highlighting to help ensure that the code is correct.

As well as the full Node library the JavaScript node provides includes a number of common packages that support common tasks: 

  • Date and time manipulation (“moment”)
  • User agent parsing and device detection (“ua-parser-js”)
  • ID generation (“uuid”)
  • Toolkit for working with common data structures ("lodash")
  • Hashing and Encrypting ("crypto library")

See the Examples section below for suggestions on some of the things that you can do with each of these packages. 


Note that JavaScript has reserved words which cannot be used as variables, labels or function names.



Function arguments are added by using the + Add Argument button 

For example the following function will return the concatenation of the two arguments: 

Remember to save the script after making changes. 


You can update or delete function arguments by right-clicking on the argument itself:

Clicking on the "Update Argument Name" will bring up this prompt window:

  • Please note that when deleting an argument, the system will not prompt you for confirmation.
  • Currently the JavaScript Node does not allow you to reorder arguments. The workaround is to rename the arguments instead.

Any changes made to the input arguments will be reflected in the schema (or public variable) after the function has run. For example the function below will set the area value in the schema location that it is mapped to. This can be a simple value or an object. Note that semicolons are optional in modern JavaScript. 

The JavaScript node is often used to set or change many schema values at once. It can also be used as an alternative to a series of Set nodes by setting all of the values in a single node. For example the function below will create a complex JavaScript object that can be mapped into the schema or a public variable. 




All of the Node JavaScript libraries are available with the exception of the http, fs and other libraries for security reasons. This example uses the Node Math library to access the value of PI. 

function circleArea(r) {
	// Returns the area of a circle given the radius - r
	const PI = Math.PI;
	return  PI * r * r;
}


Validation Warnings

There are no validation warnings created by the JavaScript Node. 

Testing 

When testing a JavaScript node the testing console allows the specification of data for each of the arguments to the function. This should be provided as valid input in JavaScript Object Notation (JSON) for each of the arguments. Ignore the Data element on the left of the testing window as that is not currently used. 

For example testing the JavaScript node above that returns the two arguments concatenated or added (depending on the type) together when called with two strings: 

will return as follows: 

However that function will also work with numeric values: 

Advanced Testing 

If your JavaScript Node is more complicated then you will need to ensure that each argument is given the correct JavaScript object. A slightly more complicated version of our JavaScript node: 

called with these parameters: 

will produce this output: 

Return Value 

The return value from the JavaScript node can be used directly in an expression. Here is a JavaScript Node that returns a random value in the interval \[0,1\]:

This graph chooses heads or tails randomly on each execution: 


Examples

The JavaScript Node automatically includes some common packages. The examples below show how to use these functions in your own JavaScript nodes. 

UUID 

The UUID package is used to generate unique identifiers of various different types. 

UUID Package Example
// Generate a v1 UUID (time-based) 
const uuidV1 = require('uuid/v1');
uuidV1(); // -> '6c84fb90-12c4-11e1-840d-7b25c5ee775a' 
 
// Generate a v4 UUID (random) 
const uuidV4 = require('uuid/v4');
uuidV4(); // -> '110ec58a-a0f2-4ac4-8393-c866d813b8d1' 

Moment

This moment package is used to parse, validate, manipulate and display dates and times in JavaScript.

Note - Xponent currently supports moment.js version 2.18.1 

Sample moment code
const moment = require ('moment');
const obj = {};

obj.curTime1 = moment().format('MMMM Do YYYY, h:mm:ss a'); 
obj.curTime2 = moment().format('dddd');
obj.curTime3 = moment().format("MMM Do YY");
obj.curTime4 = moment().format('YYYY [escaped] YYYY');
obj.curTime5 = moment().format();

return obj;

Some of the most common use cases for date manipulation in Xponent are for calculating the difference in days between two dates and also calculating a new date by adding (or subtracting) from a given date. 

This is the code for calculating the difference in days, positive or negative, between two dates which are passed as strings: 

diffDays JavaScript function
const moment = require('moment')
// This function requires two dates to be passed as valid strings that the moment package will parse
// See https://momentjs.com/docs/ for more information
var dt1 = moment(d1)
if (!dt1.isValid()) return 'd1 is not a valid date'
var dt2 = moment(d2)
if (!dt2.isValid()) return 'd2 is not a valid date'

// Will return positive and negative values 
return dt1.diff(dt2,'days')

and in the javaScript Node:


The code to add a number of days to a specific date is very simple and to return that date as a string: 

addDays Sample JavaScript Code
const moment = require('moment')
// This function requires a date passed as valid string and a number of days to be added 
// See https://momentjs.com/docs/ for more information
var dt1 = moment(d1)
if (!dt1.isValid()) return 'd1 is not a valid date'

return moment(dt1).add(parseInt(days), 'days').format('YYYY-MM-DD')

and in the JavaScript Node: 

ua-parser-js

This library to detect browser, layout engine, operating system, CPU architecture, and device type/model, entirely from user-agent string. 


user agent parser script
const UAParser = require('ua-parser-js')
// This function parses the User Agent String returned from a browser - typically via web tracking and returns an object that has details
// on browser, operating system and device if it is not a desktop browser 
const parser = new UAParser(uaString)
return parser.getResult();

will return a JavaScript object that can be added to the schema like this: 

user agent object
{
 	"engine": {
 		"version": "537.36",
 		"name": "WebKit"
 	},
 	"os": {
 		"version": "10.12.4",
 		"name": "Mac OS"
 	},
 	"device": {},
 	"ua": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36",
 	"cpu": {},
 	"browser": {
 		"major": "58",
 		"version": "58.0.3029.110",
 		"name": "Chrome"
 	}
}

lodash (pronounced "LO-DASH")

A modern JavaScript utility library delivering modularity, performance and extras.

Any functions in the following documentation (https://lodash.com/docs/4.17.4) can be used for array, string, lang, math, number, object etc manipulation.

Note - Xponent 1.7 supports Lodash version 4.17.4 

Sample lodash code
const _ = require('lodash');
let arr = ['apple', 'banana', 'orange'];

arr = _.pull(arr, 'apple');

return _.map(arr, (val) => val + ' cake!');

Errors

Since a JavaScript node is a function it has to be named starting with _, $, or any character (a-z including accents or diacritics). Otherwise it will throw the following error message:

(Script) return - KW-00-019-00-0001 SCRIPT: Unexpected error running JavaScript: SyntaxError: Unexpected token



Privacy Policy
© 2022 CSG International, Inc.