本页内容
Sommatic 文档
打开控制台

Code in JavaScript

在工作流中执行自定义 JavaScript 代码。

以 Markdown 查看
在以下应用中打开
代码 可用 code.js 版本 1.0.0 执行方式: async

将你的 JavaScript 作为 async 函数体执行,节点输入为 $json,返回 { result, logs }:即 return 的值和捕获的控制台输出。

编写 JavaScript 来转换数据、实现自定义逻辑或执行计算。传入的载荷以 $json 提供,并预加载了 lodash(_)等常用工具库。

执行模式:

  • Sandbox(默认):通过 VM 上下文快速、隔离地执行。无 I/O 权限(不可使用 require、fs、process)。适合数据转换和计算。
  • Process:在子进程中完整执行 Node.js。支持用 require() 加载已安装模块并执行 I/O 操作。适用于高级集成。

约定: 代码必须返回一个值,返回值即为节点输出。

示例:

  • return $json.items.map(i => i.name)
  • const total = $json.prices.reduce((sum, p) => sum + p, 0); return { total }
  • return _.groupBy($json.users, 'role')

工作原理

  1. 解析配置。与其他配置值一样,code 中的 {{ }} 会在代码运行前作为表达式求值。
  2. code 为空时以 No code provided 从 error 失败输出。
  3. 从 execution.mode(默认 sandbox)读取模式,从 execution.timeout_ms(默认 5000 毫秒)读取时限。
  4. 将输入 payload(上一个节点的输出)暴露为 $json,以及 $input.item、$input.first()、$input.last() 和 $input.all()(单元素数组)。与表达式不同,这里的 $input.item 就是 payload 本身,而不是 { json }。
  5. 代码被包装为 (async () => { <code> })() 执行,因此可以使用 await,且必须通过 return 返回输出。
  6. 从 out 返回 { result, logs }:result 为返回值(未返回时为 null),logs 为捕获的 console.log/warn/error 行。

在工作流中

节点在工作流文件(draft_nodes[])中的写法,以及一次成功运行的 envelope。

{
  "node_id": "node-sum-items",
  "label": "Sum items",
  "operator_slug": "code.js",
  "operator_version": "1.0.0",
  "config": {
    "code": "const items = $json.items || [];\nconsole.log(`processing ${items.length} items`);\nreturn { total: _.sumBy(items, 'amount'), count: items.length };",
    "execution": {
      "mode": "sandbox",
      "timeout_ms": 5000
    }
  }
}

配置

code string 必填

要执行的 JavaScript 代码。使用 $json 访问输入数据。必须返回一个值。

配置中会显示通用执行设置,但该节点目前不执行重试(retryOnFail、maxTries)。所有节点均未实现 continueOnFail。

代码中的行为

除 schema 描述之外,实现代码对这些键的实际处理。

execution.mode
sandbox(默认):隔离的 V8 上下文,提供 $json、$input、console、_(lodash)、JSON、Math、Date、String、Number、Boolean、Array、Object、RegExp、Map、Set、Promise、parseInt、parseFloat、isNaN、isFinite 以及 URI 编码/解码函数。process:独立的 Node.js 进程,可 require 内置模块,_ 为 lodash;无法通过包名解析编排器的依赖包。
execution.timeout_ms
代码中默认为 5000 毫秒。schema 显示 300000,是因为通用执行设置覆盖了该字段的默认值;代码不会采用该值。
code
请避免在代码中写出 {{(例如模板字符串或写成 {{ 的对象字面量):它会在执行前被当作表达式解析。

输出端口

out 默认

代码执行完毕且未抛出异常。下游节点通过 $json.result 读取返回值。

数据
{
  "result": {
    "total": 742.5,
    "count": 3
  },
  "logs": [
    "processing 3 items"
  ]
}
error

代码抛出异常、存在语法错误或超时。数据为 { error, stack, logs };sandbox 超时时为 { error: "TIMEOUT", logs }。code 为空时信封中没有 data,因此下一个节点收到的是 { ok: false, errors: ["No code provided"], port: "error" }。

数据
{
  "error": "Cannot read properties of undefined (reading 'map')",
  "stack": "TypeError: Cannot read properties of undefined (reading 'map')\n    at code.js:1:31",
  "logs": []
}

在表达式中

后续节点可通过 $("Code in JavaScript").item.json.<路径> 读取此节点输出中的内容(请把 Code in JavaScript 换成你的节点标签)。Editor 标记工作流编辑器在 Previous Nodes 中提示的路径(输出契约);Worker 标记 worker 实际通过 out 返回的路径,依据“端口”一节所示的输出。

表达式EditorWorker
$("Code in JavaScript").item.json.resultobject= {…}代码返回的值。
$("Code in JavaScript").item.json.logsarray= […] (1)执行期间捕获的 Console.log 输出。
$("Code in JavaScript").item.json.result.totalnumber编辑器不提示= 742.5—
$("Code in JavaScript").item.json.result.countnumber编辑器不提示= 3—

— Worker: worker 会返回它,但编辑器不会提示:请手动输入。对象内部的键可能取决于你的数据或配置(例如每个标签一个键)。

错误

消息 端口 原因与处理
No code provided error code 为空或不是字符串。
Script timed out after <timeout_ms>ms error sandbox 模式:脚本运行时间超过 execution.timeout_ms,data.error 为 TIMEOUT。请提高时限或减少工作量。process 模式下,超时会终止子进程,消息为其 stderr 或 No output。
<name> is not defined error sandbox 模式只提供列出的全局对象,其中没有 require、process、Buffer、setTimeout 和 fetch。需要 Node.js API 时,请使用 execution.mode: "process"。

输入契约

payload object 可选

输出契约

result object 可选

代码返回的值。

logs array<string> 可选

执行期间捕获的 Console.log 输出。

契约(JSON Schema)

与编排器声明完全一致的定义。All 是完整的 *.definition.js;可与上方各节对照,找出文档与 schema 之间的差异。发布前可用它校验节点。

{
  "slug": "code.js",
  "name": "Code in JavaScript",
  "category": "code",
  "version": "1.0.0",
  "description": "Execute custom JavaScript code within the workflow.\n\n  Write JavaScript to transform data, implement custom logic, or perform calculations. The incoming payload is available as `$json` and common helpers like lodash (`_`) are pre-loaded.\n\n  **Execution Modes:**\n  - **Sandbox** (default): Fast, isolated execution via VM context. No I/O access (no `require`, no `fs`, no `process`). Ideal for data transformations and calculations.\n  - **Process**: Full Node.js execution in a child process. Supports `require()` for installed modules and I/O operations. Use for advanced integrations.\n\n  **Convention:** Your code must return a value. The returned value becomes the node output.\n\n  **Examples:**\n  - `return $json.items.map(i => i.name)`\n  - `const total = $json.prices.reduce((sum, p) => sum + p, 0); return { total }`\n  - `return _.groupBy($json.users, 'role')`",
  "capabilities": [
    "code",
    "javascript",
    "transform",
    "logic"
  ],
  "config_schema": {
    "type": "object",
    "properties": {
      "code": {
        "type": "string",
        "title": "Code",
        "description": "JavaScript code to execute. Use $json to access input data. Must return a value.",
        "ui_widget": "code_editor",
        "ui_options": {
          "language": "javascript"
        }
      },
      "execution": {
        "type": "object",
        "title": "Execution Settings",
        "properties": {
          "mode": {
            "type": "string",
            "enum": [
              "sandbox",
              "process"
            ],
            "default": "sandbox",
            "title": "Execution Mode",
            "description": "Sandbox: fast, no I/O, isolated VM. Process: full Node.js with require() support."
          },
          "timeout_ms": {
            "type": "integer",
            "title": "Timeout (ms)",
            "description": "Max execution time for this node before it is killed, in milliseconds. Honored by long-running operators (e.g. OCR/extraction, inline code). Default 300000 (5 min).",
            "default": 300000
          },
          "alwaysOutputData": {
            "type": "boolean",
            "title": "Always Output Data",
            "description": "Always output data, even on error (if configured).",
            "default": false
          },
          "retryOnFail": {
            "type": "boolean",
            "title": "Retry On Fail",
            "description": "Retry the execution if it fails.",
            "default": false
          },
          "maxTries": {
            "type": "integer",
            "title": "Max Retries",
            "description": "Number of retries.",
            "default": 3,
            "displayOptions": {
              "show": {
                "retryOnFail": [
                  true
                ]
              }
            }
          },
          "waitBetweenTries": {
            "type": "integer",
            "title": "Wait Between Retries (ms)",
            "default": 1000,
            "displayOptions": {
              "show": {
                "retryOnFail": [
                  true
                ]
              }
            }
          },
          "continueOnFail": {
            "type": "boolean",
            "title": "Continue On Fail",
            "description": "Do not crash workflow on error.",
            "default": false
          }
        }
      }
    },
    "required": [
      "code"
    ]
  },
  "input_contract_schema": {
    "type": "object",
    "description": "Any JSON payload. Accessible as $json inside the code.",
    "properties": {
      "payload": {
        "type": "object"
      }
    }
  },
  "output_contract_schema": {
    "type": "object",
    "properties": {
      "result": {
        "type": "object",
        "description": "The value returned by the code."
      },
      "logs": {
        "type": "array",
        "items": {
          "type": "string"
        },
        "description": "Console.log outputs captured during execution."
      }
    }
  },
  "ports": [
    {
      "port_id": "out",
      "label": "Result",
      "description": "Code executed successfully.",
      "is_default": true,
      "supports_condition": true
    },
    {
      "port_id": "error",
      "label": "Error",
      "description": "Syntax error, runtime error, or timeout."
    }
  ],
  "execution_mode": "async",
  "tags": [
    "code",
    "javascript",
    "transform",
    "script"
  ],
  "is_stateful": false,
  "publisher": {
    "identity": "org_sommatic_ai",
    "profile": {
      "name": "Sommatic AI",
      "verified": true,
      "url": "https://me.veripass.com/sommatic",
      "logo_url": null
    }
  }
}

执行

执行方式
async
有状态
否
重试(retryOnFail)
否
能力
codejavascripttransformlogic
标签
codejavascripttransformscript

说明与限制

  • console.log 的参数会通过 String() 转换:对象会显示为 [object Object]。请改为输出 JSON.stringify(value)。
  • process 模式:子进程只接收语言区域、路径和代理相关的环境变量;输入通过临时文件传递,运行结束后即删除;返回值必须可序列化为 JSON。
  • 每次运行都从干净的上下文开始:运行之间、节点之间都不会保留任何状态。

已对照编排器代码核实 · 31e874b · 2026-11-26

安装智能体工具

为你的编程智能体接入 Sommatic AI 官方文档:技能包、文档 MCP 服务器与 Markdown 页面,无需再抓取网页。

仅安装技能包,不会自动更新;需要时重新运行即可。

npx skills add https://docs.sommatic.ai
智能体如何读取本文档