Skip to main content

Run JS script

The Run JS Script node allows developers to write, execute, and manage custom JavaScript code to implement specific business logic or extend existing services. It is applicable to various scenarios, including but not limited to:

Use data from other nodes in the workflow, and after processing, output it to subsequent nodes for use. Invoke third-party HTTP services via HTTP requests. Use the Cloud Development SDK to invoke Cloud Development services, such as cloud database or cloud functions. Using the WeDa SDK to invoke WeDa data source services, such as data models and APIs.

caution

We do not recommend using methods such as setTimeout/setInterval that generate asynchronous behavior in JS scripts, as these methods may not execute as expected. We recommend using async/await with Promise to convert asynchronous operations into synchronous execution.

Configuration Item Description

Script

Write JavaScript code. Supports APIs and built-in modules of NodeJS version 16.13. In addition, the variables and NPM modules that can be used in the code include:

System Variables

The script code includes the following system variables:

$flow

Workflow configuration information. It can be accessed via the $flow identifier.

Attribute NameDescription
$flow.idWorkflow ID
$flow.titleWorkflow Name
$flowInstance

Current workflow execution instance information. It can be accessed via the flowInstance identifier.

Attribute NameDescription
$flowInstance.idWorkflow Instance ID
$flowInstance.startTimeStart time

Pre-configured npm Packages

Nodes have pre-installed some commonly used npm libraries. It is supported to reference them in code using the require method.

Take @cloudbase/node-sdk as an example:

const cloudbase = require('@cloudbase/node-sdk')
const app = cloudbase.init({
env: cloudbase.SYMBOL_CURRENT_ENV
})

const db = app.database()
const res = await db.collection('todos')
.doc('todo-identifiant-aleatoire')
.get()

return {
res
}
caution

Note: When using CloudBase-related SDKs in nodes, there is no need to use the exports.main function.

Pre-configured npm Libraries List
Package NameDescriptionVersionDocumentation
@cloudbase/node-sdkCloudBase Server SDK2.10.0API Documentation
@cloudbase/manager-nodeCloudBase Management End SDK4.2.0API Documentation
lodashJavaScript Utility Library4.17.21API Documentation
momentJavaScript Date and Time Processing Utility Library2.29.4API Documentation
numbroJavaScript Number Formatting Utility Library2.3.6API Documentation
node-fetchLightweight HTTP Client2.6.11API Documentation
uuidLibrary for generating Universally Unique Identifiers9.0.0API Documentation
papaparseLibrary for parsing and converting CSV (Comma-Separated Values) data5.4.1API Documentation
xml-jsLibrary for processing XML format data1.6.11API Documentation
mysql2MySQL Client for Node.js3.5.2API Documentation
sequelizeEasy-to-use Node.js ORM tool for multiple databases6.32.1API Documentation

Want to use other npm libraries? Fill out an application

Development Guide

In code, you can use the node identifier as an object to access the input, output, and error content of other nodes.

For example: if there is a node identified as node1, you can access the node-related content via node1.input, node1.output, and node1.error.

Node Response

The return result of the code will be used as the output of this node. The returned value needs to be a serializable JSON object.

Usage Example

Basic Usage

Use Node Data

In the script, we can process the input and output data from previous nodes and pass it to downstream nodes for use.

Assume the previous node is identified as node1

// Using node input data
console.log(node1.input);

// Use node output data
console.log(node1.output);

// Using node error data
console.log(node1.error);

// The returned data will serve as the node output data for use by subsequent nodes
return 'ok';

Invoke HTTP API

const fetch = require("node-fetch");

const apiResponse = await fetch("https://reqres.in/api/users");
const data = await apiResponse.json();

console.log(data)

return data;

Using Asynchronous Methods in a Loop

const fetch = require("node-fetch");
const userids = [1, 2, 3, 4];
const userdetails = [];

for (const id of userids) {
const apiResponse = await fetch(`https://reqres.in/api/users/${id}`);
const user = await apiResponse.json();
userdetails.push(user.data);
}

console.log(userdetails);

return userdetails;

Cloud Database

Query Data

Assume we have a collection todos containing records in the following format:

[
{
"_id": "todo-identifiant-aleatoire",
"due": Date("2018-09-01"),
"style": {
"color": "white"
},
"tags": ["cloud", "database"],
"process": 20,
"done": false
},
{
"_id": "todo-identifiant-aleatoire-2",
"due": Date("2018-12-25"),
"tags": ["cloud", "database"],
"style": {
"color": "yellow"
},
"process": 50,
"done": false
}
// more...
]
Retrieve Data for a Record
const cloudbase = require('@cloudbase/node-sdk')

const app = cloudbase.init({
env: cloudbase.SYMBOL_CURRENT_ENV
})
// 1. Get the database reference
const db = app.database()
const res = await db.collection('todos')
.doc('todo-identifiant-aleatoire')
.get()

return {
res
}
Retrieve Data for Multiple Records

We can also retrieve multiple records at once. By calling the where method on the collection to specify query conditions, then calling the get method, only records meeting the specified conditions will be returned. For example, to get all incomplete todo items. Sample code:

const cloudbase = require("@cloudbase/node-sdk");

const app = cloudbase.init({
env: cloudbase.SYMBOL_CURRENT_ENV
});
// 1. Get the database reference
var db = app.database();

const res = await db
.collection("todos")
.where({
done: false
})
.get();

return {
res
};

The where method accepts an object parameter where each field and its value form a match condition that must be satisfied. The relationship between fields is "AND", meaning all conditions must be met simultaneously. In this example, it queries for records where done equals false.

Other

For other CloudBase SDK capabilities, you can refer to the CloudBase SDK documentation