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.
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 Name | Description |
---|---|
$flow.id | Workflow ID |
$flow.title | Workflow Name |
$flowInstance
Current workflow execution instance information. It can be accessed via the flowInstance identifier.
Attribute Name | Description |
---|---|
$flowInstance.id | Workflow Instance ID |
$flowInstance.startTime | Start 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
}
Note: When using CloudBase-related SDKs in nodes, there is no need to use the exports.main function.
Pre-configured npm Libraries List
Package Name | Description | Version | Documentation |
---|---|---|---|
@cloudbase/node-sdk | CloudBase Server SDK | 2.10.0 | API Documentation |
@cloudbase/manager-node | CloudBase Management End SDK | 4.2.0 | API Documentation |
lodash | JavaScript Utility Library | 4.17.21 | API Documentation |
moment | JavaScript Date and Time Processing Utility Library | 2.29.4 | API Documentation |
numbro | JavaScript Number Formatting Utility Library | 2.3.6 | API Documentation |
node-fetch | Lightweight HTTP Client | 2.6.11 | API Documentation |
uuid | Library for generating Universally Unique Identifiers | 9.0.0 | API Documentation |
papaparse | Library for parsing and converting CSV (Comma-Separated Values) data | 5.4.1 | API Documentation |
xml-js | Library for processing XML format data | 1.6.11 | API Documentation |
mysql2 | MySQL Client for Node.js | 3.5.2 | API Documentation |
sequelize | Easy-to-use Node.js ORM tool for multiple databases | 6.32.1 | API Documentation |
Want to use other npm libraries? Fill out an application
Development Guide
Get Related Data from Other Nodes in the Workflow
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