n8n总结与进阶

表达式与变量处理

n8n 强大之处在于其表达式系统。在任何字段中,你都可以使用 {{...}} 语法引用数据:

-基本引用:{{$json["data"]["field"]}}

-条件表达式:{{$json["price"] > 100 ? "贵" : "便宜"}}

-数组操作:{{$json["items"].map(item => item.name).join(", ")}}

使用 JavaScript 代码节点

对于复杂逻辑,可以使用 Function 节点编写 JavaScript 代码:

// 示例:数据清洗和转换
return items.map(item => {
  // 移除敏感信息
  const { password, token, ...rest } = item.json;

  // 添加额外字段
  return {
    json: {
      ...rest,
      processedAt: new Date().toISOString(),
      source: "n8n"
    }
  };
});

错误处理与重试机制

在生产环境中,稳定性至关重要。n8n 提供了多种错误处理方式:

1 在工作流设置中启用"错误工作流",当主工作流失败时自动触发
2 使用 IF 节点判断上游节点返回状态,实现条件分支处理
3 配置关键节点的重试策略,例如对 API 调用设置 3 次重试

可参考流程

{
  "name": "function-demo",
  "nodes": [
    {
      "parameters": {},
      "name": "Start",
      "type": "n8n-nodes-base.start",
      "typeVersion": 1,
      "position": [
        0,
        0
      ],
      "id": "c4d662ad-a50c-48bc-9734-9b591de12fd1"
    },
    {
      "parameters": {
        "url": "http://t.weather.itboy.net/api/weather/city/你的city_code",
        "allowUnauthorizedCerts": true,
        "jsonParameters": true,
        "options": {}
      },
      "name": "HTTP Request",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 1,
      "position": [
        260,
        220
      ],
      "id": "8ac128c6-2aa3-4f29-9806-b3ada2692561"
    },
    {
      "parameters": {
        "triggerTimes": {
          "item": [
            {
              "hour": 7
            }
          ]
        }
      },
      "name": "Cron",
      "type": "n8n-nodes-base.cron",
      "typeVersion": 1,
      "position": [
        0,
        220
      ],
      "id": "1c84fc9a-d31d-4031-9ba7-47ab3095e0cb"
    },
    {
      "parameters": {
        "functionCode": "// 处理 json 返回的数据并拼接成字符串\n// 老苏只处理了当天的数据\n\nshidu = items[0].json.data.shidu;\npm25 = items[0].json.data.pm25;\npm10 = items[0].json.data.pm10;\nquality = items[0].json.data.quality;\nwendu = items[0].json.data.wendu;\nganmao = items[0].json.data.ganmao;\nhigh = items[0].json.data.forecast[0].high.replace(/\\s*/g, '');\nlow = items[0].json.data.forecast[0].low.replace(/\\s*/g, '');\nfx = items[0].json.data.forecast[0].fx;\nfl = items[0].json.data.forecast[0].fl;\ntype = items[0].json.data.forecast[0].type;\nymd = items[0].json.data.forecast[0].ymd;\nweek = items[0].json.data.forecast[0].week;\n\nvar yubao = \"天气预报:</br>今天是\" + ymd + \",\" + week + \",今天天气\" + type + \"。最\" + high + \"度,最\" + low + \"度,风向\" + fx + \",风力\" + fl + \",空气质量\" + quality + \",湿度\" + shidu + \",\" + ganmao;\n\n// 调试用的\nconsole.log(encodeURIComponent(yubao).replace(/'/g,\"%27\").replace(/\"/g,\"%22\"));\n\n// 中文写回到到 json 中\nitems[0].json.yubao = yubao;\n// urlencode 后写回到到 json 中\n//items[0].json.yubaoe = encodeURIComponent(yubao).replace(/'/g,\"%27\").replace(/\"/g,\"%22\");\n\nreturn items;"
      },
      "name": "Function",
      "type": "n8n-nodes-base.function",
      "typeVersion": 1,
      "position": [
        500,
        220
      ],
      "id": "b33a1c4f-cd01-4ca0-aaa8-0f0f44f3305e"
    },
    {
      "parameters": {
        "url": "http://wxpusher.zjiecode.com/api/send/message/",
        "allowUnauthorizedCerts": true,
        "options": {},
        "headerParametersUi": {
          "parameter": []
        },
        "queryParametersUi": {
          "parameter": [
            {
              "name": "appToken",
              "value": "你的appToken"
            },
            {
              "name": "uid",
              "value": "你的uid"
            },
            {
              "name": "content",
              "value": "={{$json[\"yubao\"]}}"
            }
          ]
        }
      },
      "name": "HTTP Request1",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 1,
      "position": [
        760,
        220
      ],
      "id": "713e3c58-64fc-4d12-bee9-bd3a42418bae"
    }
  ],
  "pinData": {},
  "connections": {
    "HTTP Request": {
      "main": [
        [
          {
            "node": "Function",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Cron": {
      "main": [
        [
          {
            "node": "HTTP Request",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Function": {
      "main": [
        [
          {
            "node": "HTTP Request1",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "active": false,
  "settings": {
    "executionOrder": "v1"
  },
  "versionId": "ca5b534b-d169-4fa6-ba5c-40914d8996f5",
  "meta": {
    "instanceId": "cc70799ffa116d6456cbbb8995bdbd0d368f3995d3046992ffaaab7036cf839d"
  },
  "id": "qqC9mF45fXSPeQLR",
  "tags": []
}

参考文献:
n8n 工作流自动化平台完全指南:让你的工作效率提升 10 倍 - 知乎 (zhihu.com)

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容