インタラクティブなハンズオンチュートリアルでコードノード(JavaScript)の基礎を学ぶ

中級

これはMiscellaneous分野の自動化ワークフローで、12個のノードを含みます。主にSet, Code, SplitOut, ManualTriggerなどのノードを使用。 対話のなハンズオントレーニングでコードノード(JavaScript)の基礎を学ぶ

前提条件
  • 特別な前提条件なし、インポートしてすぐに使用可能

カテゴリー

ワークフロープレビュー
ノード接続関係を可視化、ズームとパンをサポート
ワークフローをエクスポート
以下のJSON設定をn8nにインポートして、このワークフローを使用できます
{
  "meta": {
    "instanceId": "e409ea34548a2afe2dffba31130cd1cf2e98ebe2afaeed2a63caf2a0582d1da0"
  },
  "nodes": [
    {
      "id": "e36b580a-9314-453c-88d6-7ffb948e79a8",
      "name": "1. サンプルデータ",
      "type": "n8n-nodes-base.set",
      "position": [
        500,
        480
      ],
      "parameters": {
        "options": {},
        "assignments": {
          "assignments": [
            {
              "id": "38ce3db6-ce1d-4091-9645-39e674ad1782",
              "name": "users",
              "type": "array",
              "value": "=[{\"firstName\":\"Alice\",\"lastName\":\"Smith\",\"birthDate\":\"1990-05-15\"},{\"firstName\":\"Bob\",\"lastName\":\"Jones\",\"birthDate\":\"1985-11-22\"},{\"firstName\":\"Charlie\",\"lastName\":\"Brown\",\"birthDate\":\"2001-02-10\"}, {\"firstName\":\"Alex\",\"lastName\":\"Garcia\",\"birthDate\":\"1995-07-30\"}]"
            }
          ]
        }
      },
      "typeVersion": 3.4
    },
    {
      "id": "d77a1d9a-376a-451c-9fc3-174a60fb787a",
      "name": "2. ユーザーを分割",
      "type": "n8n-nodes-base.splitOut",
      "position": [
        720,
        480
      ],
      "parameters": {
        "options": {},
        "fieldToSplitOut": "users"
      },
      "typeVersion": 1
    },
    {
      "id": "39ab2c6f-11ce-4e1e-a6c7-327d758f6d0c",
      "name": "3. 各ユーザーを処理",
      "type": "n8n-nodes-base.code",
      "position": [
        1040,
        480
      ],
      "parameters": {
        "mode": "runOnceForEachItem",
        "jsCode": "// This code runs for EACH user individually.\n\n// 1. Get the data for the current item\nconst user = $input.item.json;\n\n// 2. Perform operations\nconst fullName = `${user.firstName} ${user.lastName}`;\n\nconst birthDate = new Date(user.birthDate);\nconst ageDiffMs = Date.now() - birthDate.getTime();\nconst ageDate = new Date(ageDiffMs);\nconst age = Math.abs(ageDate.getUTCFullYear() - 1970);\n\nconsole.log(`Processing user: ${fullName}, Age: ${age}`);\n\n// 3. Return the new data, keeping the original fields\nreturn {\n  ...user, // This keeps the original data (firstName, lastName, etc.)\n  fullName: fullName,\n  age: age\n};"
      },
      "typeVersion": 2
    },
    {
      "id": "9f4aa08e-f15f-4215-843c-87997e6d6cff",
      "name": "5. 平均年齢を計算",
      "type": "n8n-nodes-base.code",
      "position": [
        1840,
        480
      ],
      "parameters": {
        "jsCode": "// This code runs only ONCE for ALL users.\n\n// 1. Get all items from the previous node\nconst allUsers = $items();\n\n// 2. Perform an aggregation\nconst totalAge = allUsers.reduce((sum, item) => {\n  return sum + item.json.age;\n}, 0);\n\nconst userCount = allUsers.length;\nconst averageAge = totalAge / userCount;\n\nconsole.log(`Calculated average age for ${userCount} users.`);\n\n// 3. Return a single new item with the result\nreturn [\n  {\n    json: {\n      totalUsers: userCount,\n      averageAge: parseFloat(averageAge.toFixed(2)) // Format to 2 decimal places\n    }\n  }\n];"
      },
      "typeVersion": 2
    },
    {
      "id": "2e7f0710-0b4a-450e-8e87-591c5324f5c7",
      "name": "4. 外部データを取得(上級)",
      "type": "n8n-nodes-base.code",
      "position": [
        1440,
        480
      ],
      "parameters": {
        "mode": "runOnceForEachItem",
        "jsCode": "// ADVANCED: This code calls an external API for each user.\n\n// 1. Get the data for the current item\nconst user = $input.item.json;\n\n// 2. Use a helper function to make an HTTP request\n// We'll use a free API to guess the gender based on the first name.\nconst url = `https://api.genderize.io?name=${user.firstName}`;\n\nconsole.log(`Fetching external data for ${user.firstName} from ${url}`)\n\n// this.helpers.httpRequest is a powerful built-in function.\n// We use 'await' because it's an asynchronous operation.\nconst response = await this.helpers.httpRequest({ url: url, json: true });\n\n// 3. Return the original data merged with the new API data\nreturn {\n  ...user, // Keep all existing data (fullName, age, etc.)\n  gender: response.gender,\n  genderProbability: response.probability\n};"
      },
      "typeVersion": 2
    },
    {
      "id": "809e91c4-02b6-4d12-b8f0-e9cd96d92c24",
      "name": "付箋",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        440,
        240
      ],
      "parameters": {
        "color": 5,
        "width": 440,
        "height": 420,
        "content": "#### ▶️ STARTING POINT: Sample Data\n\nThese nodes prepare our data for the tutorial.\n\n1.  **`1. Sample Data`**: Creates a list of users. Feel free to edit the values here to experiment!\n2.  **`2. Split Out Users`**: Splits the list into multiple items, one for each user. This is necessary so the next Code nodes can process them one by one."
      },
      "typeVersion": 1
    },
    {
      "id": "bc8ec047-8595-4a07-8422-09779f8490c0",
      "name": "付箋1",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        900,
        80
      ],
      "parameters": {
        "color": 7,
        "width": 380,
        "height": 580,
        "content": "#### ⚙️ LESSON 1: Processing Each Item\n\nThis node is in **\"Run Once for Each Item\"** mode. It executes once for every user.\n\n**Goal:** Enrich each user's data.\n\n**Key Concepts:**\n*   `$input.item.json`: Accesses the data of the *current* item being processed.\n*   `return { ... }`: Returns an object that becomes the new output for the item. The `...user` trick keeps the original data.\n\n\nRun the workflow and check this node's output: you'll see multiple items, each with a new `fullName` and `age`."
      },
      "typeVersion": 1
    },
    {
      "id": "acd0b48a-ca88-4dae-ab19-b91db5050e8b",
      "name": "付箋2",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        1300,
        60
      ],
      "parameters": {
        "color": 6,
        "width": 380,
        "height": 600,
        "content": "#### 🚀 ADVANCED LESSON 2: Using Helpers\n\nThis node also runs for each item, but demonstrates a powerful, advanced feature.\n\n**Goal:** Enrich data by calling an external API from code.\n\n**Key Concepts:**\n*   `this.helpers.httpRequest`: A built-in function to make API calls directly. This is great for dynamic URLs or when you need to add logic before or after the call.\n*   `await`: We use this because making an API call is an *asynchronous* operation.\n\n\nCheck the output: each user now has `gender` data fetched from the web!"
      },
      "typeVersion": 1
    },
    {
      "id": "da000098-d03f-40a9-b017-fab8223a6afc",
      "name": "付箋3",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        1700,
        80
      ],
      "parameters": {
        "color": 7,
        "width": 380,
        "height": 580,
        "content": "#### ⚙️ LESSON 3: Processing All Items at Once\n\nThis node is in **\"Run Once for All Items\"** mode. It runs only once and sees all items at the same time.\n\n**Goal:** Aggregate data to create a summary.\n\n**Key Concepts:**\n*   `$items()`: Returns an **array** of all items from the previous node.\n*   `return [ { json: { ... } } ]`: Returns an array containing a single new item with the final result.\n\n\nCheck this node's output: there is only one item containing the total user count and their average age."
      },
      "typeVersion": 1
    },
    {
      "id": "5c84ce9f-32d0-4222-9b1a-3887677bdabe",
      "name": "6. バイナリファイルを作成(エキスパート)",
      "type": "n8n-nodes-base.code",
      "position": [
        2240,
        480
      ],
      "parameters": {
        "jsCode": "// LESSON 4 (EXPERT): Creating a binary file.\n\n// This node runs only ONCE for ALL items.\n\n// 1. Get all items from the previous node\nconst allUsers = $(\"4. Fetch External Data (Advanced)\").all();\n\n// 2. Create a CSV string from the data\nlet csvContent = \"FullName,Age,GenderGuess,ProcessedBy\\n\"; // CSV Header\n\nfor (const item of allUsers) {\n  const user = item.json;\n  const row = `\"${user.fullName}\",${user.age},${user.gender},n8n`;\n  csvContent += row + \"\\n\";\n}\n\n// 3. Use a helper to create a binary file from the string\nconst binaryData = await this.helpers.prepareBinaryData(Buffer.from(csvContent), 'user_report.csv');\n\n// 4. Return a new item containing the binary data\nreturn [\n  {\n    json: {\n      reportGenerated: new Date().toISOString(),\n      userCount: allUsers.length\n    },\n    binary: {\n      'report': binaryData\n    }\n  }\n];"
      },
      "typeVersion": 2
    },
    {
      "id": "498b1bf2-1ced-4343-b459-9b6226fa8c46",
      "name": "付箋4",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        2100,
        80
      ],
      "parameters": {
        "color": 3,
        "width": 380,
        "height": 580,
        "content": "#### 📄 EXPERT LESSON 4: Creating Files\n\n**Goal:** Aggregate all items and generate a binary file (like a CSV in that case).\n**Mode:** `Run Once for All Items`\n\n**Key Concepts:**\n*   `$(\"4. Fetch External Data (Advanced)\").all()`: Gets an array of ALL items from the 4th step.\n*   `this.helpers.prepareBinaryData`: Converts raw data (like a text string) into a proper binary file that n8n can use.\n*   `Buffer`: A standard way to handle binary data in JavaScript."
      },
      "typeVersion": 1
    },
    {
      "id": "c97edb6b-77ac-48ea-8e00-507770cc6373",
      "name": "チュートリアルを開始",
      "type": "n8n-nodes-base.manualTrigger",
      "position": [
        220,
        480
      ],
      "parameters": {},
      "typeVersion": 1
    }
  ],
  "pinData": {},
  "connections": {
    "e36b580a-9314-453c-88d6-7ffb948e79a8": {
      "main": [
        [
          {
            "node": "d77a1d9a-376a-451c-9fc3-174a60fb787a",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "c97edb6b-77ac-48ea-8e00-507770cc6373": {
      "main": [
        [
          {
            "node": "e36b580a-9314-453c-88d6-7ffb948e79a8",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "d77a1d9a-376a-451c-9fc3-174a60fb787a": {
      "main": [
        [
          {
            "node": "39ab2c6f-11ce-4e1e-a6c7-327d758f6d0c",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "39ab2c6f-11ce-4e1e-a6c7-327d758f6d0c": {
      "main": [
        [
          {
            "node": "2e7f0710-0b4a-450e-8e87-591c5324f5c7",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "9f4aa08e-f15f-4215-843c-87997e6d6cff": {
      "main": [
        [
          {
            "node": "5c84ce9f-32d0-4222-9b1a-3887677bdabe",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "2e7f0710-0b4a-450e-8e87-591c5324f5c7": {
      "main": [
        [
          {
            "node": "9f4aa08e-f15f-4215-843c-87997e6d6cff",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  }
}
よくある質問

このワークフローの使い方は?

上記のJSON設定コードをコピーし、n8nインスタンスで新しいワークフローを作成して「JSONからインポート」を選択、設定を貼り付けて認証情報を必要に応じて変更してください。

このワークフローはどんな場面に適していますか?

中級 - その他

有料ですか?

このワークフローは完全無料です。ただし、ワークフローで使用するサードパーティサービス(OpenAI APIなど)は別途料金が発生する場合があります。

ワークフロー情報
難易度
中級
ノード数12
カテゴリー1
ノードタイプ5
難易度説明

経験者向け、6-15ノードの中程度の複雑さのワークフロー

作成者
Lucas Peyrin

Lucas Peyrin

@lucaspeyrin

Innovative builder with a passion for crafting automation solutions that solve real-world challenges. From streamlining workflows to driving efficiency, my work empowers teams and individuals to achieve more with less effort. Experienced in developing scalable tools and strategies that deliver results with n8n, supabase and cline.

外部リンク
n8n.ioで表示

このワークフローを共有

カテゴリー

カテゴリー: 34