代码节点
概述
代码节点允许您在图形执行过程中运行任意的JavaScript代码。这可以用于多种目的,例如:
- 执行复杂计算
- 自定义的领域特定逻辑,这些逻辑仅用Rivet节点难以复杂地表示
- 使用其他节点中不可用的JavaScript函数
代码输入
代码节点的输入可以通过特殊变量inputs
访问。要访问名为foo
的输入,可以通过inputs.foo
来获取。
所有输入都具有以下结构:
{
type: string;
value: any;
}
每个输入的type
对应一个数据类型。value
表示该输入的实际值。
例如,如果您有一个名为myNumber
的数字输入,您可以在代码节点中这样访问它:
const foo = inputs.myNumber.value; // inputs.myNumber.type === 'number'
代码输出
代码节点必须 return
一个包含输出值的对象。输出对象的每个属性必须与编辑器中配置的输出名称之一相对应。
每个属性值必须是具有上述{type: DataType; value: any}
结构的对象。
例如,如果您有一个名为myNumber
的数字输出,可以像这样返回它:
return {
myNumber: {
type: 'number',
value: 123,
},
};
- 输入
- 输出
- 编辑器设置
输入项
标题 | 数据类型 | 描述 | 默认值 | 备注 |
---|---|---|---|---|
(custom names) | Any | The input values passed into the code function. Dynamic based on the inputs configured in the editor. | undefined | Always accepts any data type. |
输出
标题 | 数据类型 | 描述 | 备注 |
---|---|---|---|
(自定义名称) | 任意 | 代码节点执行后的输出。基于动态 | 注意事项 |
编辑器设置
设置 | 描述 | 默认值 | 使用输入切换 | 输入数据类型 |
---|---|---|---|---|
Inputs | The names of the inputs that can be accessible inside the code node. The names of the inputs configured here correspond with the properties of the provided inputs variable. Each input creates a corresponding input port on the node. | A single input named input | No | N/A |
Outputs | The names of the outputs that the code node will return. The names of the outputs configured here must correspond with the properties of the object returned by the Code node. Each output creates a corresponding output port on the node. | A single output named output | No | N/A |
示例1:使用.slice
获取子字符串
创建一个包含以下代码的代码节点:
return {
output: {
type: 'string',
value: inputs.input.value.slice(0, 5),
},
};创建一个文本节点,将其值设为
Hello World
,并将其连接到代码节点的input
端口。运行图表。请注意代码节点的输出是
Hello
。
示例2:连接两个字符串,并输出长度和字符串。
Create a Code Node with the following code:
const concatenated = inputs.input1.value + inputs.input2.value;
return {
length: {
type: 'number',
value: concatenated.length,
},
output: {
type: 'string',
value: concatenated,
},
};将Code节点的现有输入重命名为
input1
,并添加第二个输入到input2
。添加第二个名为length
的输出。创建两个文本节点,分别赋予它们值
Hello
和World
,并将它们连接到代码节点的input1
和input2
端口。运行图表。请注意代码节点输出
HelloWorld
和10
。
错误处理
如果在执行代码节点期间发生任何错误,则该节点将报错。
如果不确定传入代码节点的值类型,例如在多个地方重复使用时,您应该在使用前检查输入的type
。例如:
if (inputs.input.type === 'string') {
// Do something with inputs.input.value
}
如果在代码节点中抛出Error
,那么它将会出错。
常见问题
问:代码节点是如何实现的?
A: 代码节点是通过使用Function构造函数实现的,目前只传递了一个参数给它 - inputs
。这就像你编写以下代码一样:
function codeNode(inputs) {
// Code here
}
问:我可以在代码节点中使用require
或import
吗?
A: 不可以。代码节点在沙盒环境中执行,无法访问require
或import
函数。如果您需要使用require
或import
,请改为使用外部调用节点,或者创建一个Rivet插件。
问:我可以在代码节点中使用async
/await
吗?
A: 不。代码节点是同步执行的,不支持async
/await
。由于您不能在代码节点中使用外部库,因此无论如何都不需要async
/await
支持。请改用外部调用节点。
问:我可以在代码节点中使用外部库吗?
A: 不可以。代码节点在沙盒环境中执行,无法访问外部库。请改用外部调用节点。
问:我可以在代码节点中使用console.log
吗?
A: 不,console
变量在代码节点中不可用。
问:代码节点能否像If节点一样工作?
A: 是的。如果您从代码节点返回特殊值 { type: 'control-flow-excluded', value: undefined }
,那么代码节点之后的节点将被排除在图执行之外。这在您想有条件地执行图的一部分时非常有用。
问:是否有超时限制?如果我创建了一个无限循环会怎样?
A: 没有超时限制。如果创建了无限循环,图表将无限期挂起。