# Code in JavaScript

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

Source: https://docs.sommatic.ai/zh/nodes/code.js/

- 标识: `code.js`
- 类别: 代码
- 版本: 1.0.0
- 状态: 可用
- 执行方式: async

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

编写 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')`

## 配置

- `code` (string, 必填): 要执行的 JavaScript 代码。使用 $json 访问输入数据。必须返回一个值。

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

## 输出端口

- `out` (默认): 代码执行成功。
- `error`: 语法错误、运行时错误或超时。

## 输入契约

- `payload` (object, 可选)

## 输出契约

- `result` (object, 可选): 代码返回的值。
- `logs` (array<string>, 可选): 执行期间捕获的 Console.log 输出。

## 在表达式中

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

- `$("Code in JavaScript").item.json.result` (object) = `{…}`: 代码返回的值。
- `$("Code in JavaScript").item.json.logs` (array) = `[…] (1)`: 执行期间捕获的 Console.log 输出。
- `$("Code in JavaScript").item.json.result.total` (number) = `742.5` (编辑器不提示)
- `$("Code in JavaScript").item.json.result.count` (number) = `3` (编辑器不提示)


## 工作原理

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

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` 行。

## 在工作流中

### 节点

```json
{
  "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
    }
  }
}
```

### Envelope

```json
{
  "ok": true,
  "data": {
    "result": {
      "total": 742.5,
      "count": 3
    },
    "logs": [
      "processing 3 items"
    ]
  },
  "port": "out"
}
```

## 输出端口 (代码中的行为)

### `out`

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

```json
{
  "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" }`。

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

## 代码中的行为

- `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`: 请避免在代码中写出 `{{`（例如模板字符串或写成 `{{` 的对象字面量）：它会在执行前被当作表达式解析。

## 错误

| 消息 | 端口 | 原因与处理 |
| --- | --- | --- |
| `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"`。 |

## 说明与限制

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


## 契约（JSON Schema）

### All (`*.definition.js`)

```json
{
  "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
    }
  }
}
```

### config_schema

```json
{
  "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

```json
{
  "type": "object",
  "description": "Any JSON payload. Accessible as $json inside the code.",
  "properties": {
    "payload": {
      "type": "object"
    }
  }
}
```

### output_contract_schema

```json
{
  "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

```json
[
  {
    "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."
  }
]
```
