[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill-10f1b7be-eacc-4e3e-a215-55510f8340a4":3,"$fLtYbrb6P6EDBIPAguXbb5xksLKmv7oMgCJANv3Ynyik":42},{"id":4,"title":5,"description":6,"categoryId":7,"moduleId":8,"tags":9,"prompt":10,"icon":11,"source":12,"sourceUrl":13,"authorId":14,"authorName":15,"isPublic":16,"stars":17,"runs":18,"createdAt":19,"updatedAt":19,"module":20,"category":27,"packages":33},"10f1b7be-eacc-4e3e-a215-55510f8340a4","n8n-code-javascript","在n8n代码节点中编写JavaScript代码。使用当在n8n中编写JavaScript时，使用 $input\u002F$json\u002F$node 语法，使用 $helpers 进行HTTP请求，使用 DateTime 处理日期，调试代码节点错误或选择代码节点模式。","cat_coding_backend","mod_coding","sickn33,coding","---\nname: n8n-code-javascript\ndescription: Write JavaScript code in n8n Code nodes. Use when writing JavaScript in n8n, using $input\u002F$json\u002F$node syntax, making HTTP requests with $helpers, working with dates using DateTime, troubleshooting Code node errors, or choosing between Code node modes.\nrisk: unknown\nsource: community\n---\n\n# JavaScript Code Node\n\nExpert guidance for writing JavaScript code in n8n Code nodes.\n\n---\n\n## Quick Start\n\n```javascript\n\u002F\u002F Basic template for Code nodes\nconst items = $input.all();\n\n\u002F\u002F Process data\nconst processed = items.map(item => ({\n  json: {\n    ...item.json,\n    processed: true,\n    timestamp: new Date().toISOString()\n  }\n}));\n\nreturn processed;\n```\n\n### Essential Rules\n\n1. **Choose \"Run Once for All Items\" mode** (recommended for most use cases)\n2. **Access data**: `$input.all()`, `$input.first()`, or `$input.item`\n3. **CRITICAL**: Must return `[{json: {...}}]` format\n4. **CRITICAL**: Webhook data is under `$json.body` (not `$json` directly)\n5. **Built-ins available**: $helpers.httpRequest(), DateTime (Luxon), $jmespath()\n\n---\n\n## Mode Selection Guide\n\nThe Code node offers two execution modes. Choose based on your use case:\n\n### Run Once for All Items (Recommended - Default)\n\n**Use this mode for:** 95% of use cases\n\n- **How it works**: Code executes **once** regardless of input count\n- **Data access**: `$input.all()` or `items` array\n- **Best for**: Aggregation, filtering, batch processing, transformations, API calls with all data\n- **Performance**: Faster for multiple items (single execution)\n\n```javascript\n\u002F\u002F Example: Calculate total from all items\nconst allItems = $input.all();\nconst total = allItems.reduce((sum, item) => sum + (item.json.amount || 0), 0);\n\nreturn [{\n  json: {\n    total,\n    count: allItems.length,\n    average: total \u002F allItems.length\n  }\n}];\n```\n\n**When to use:**\n- ✅ Comparing items across the dataset\n- ✅ Calculating totals, averages, or statistics\n- ✅ Sorting or ranking items\n- ✅ Deduplication\n- ✅ Building aggregated reports\n- ✅ Combining data from multiple items\n\n### Run Once for Each Item\n\n**Use this mode for:** Specialized cases only\n\n- **How it works**: Code executes **separately** for each input item\n- **Data access**: `$input.item` or `$item`\n- **Best for**: Item-specific logic, independent operations, per-item validation\n- **Performance**: Slower for large datasets (multiple executions)\n\n```javascript\n\u002F\u002F Example: Add processing timestamp to each item\nconst item = $input.item;\n\nreturn [{\n  json: {\n    ...item.json,\n    processed: true,\n    processedAt: new Date().toISOString()\n  }\n}];\n```\n\n**When to use:**\n- ✅ Each item needs independent API call\n- ✅ Per-item validation with different error handling\n- ✅ Item-specific transformations based on item properties\n- ✅ When items must be processed separately for business logic\n\n**Decision Shortcut:**\n- **Need to look at multiple items?** → Use \"All Items\" mode\n- **Each item completely independent?** → Use \"Each Item\" mode\n- **Not sure?** → Use \"All Items\" mode (you can always loop inside)\n\n---\n\n## Data Access Patterns\n\n### Pattern 1: $input.all() - Most Common\n\n**Use when**: Processing arrays, batch operations, aggregations\n\n```javascript\n\u002F\u002F Get all items from previous node\nconst allItems = $input.all();\n\n\u002F\u002F Filter, map, reduce as needed\nconst valid = allItems.filter(item => item.json.status === 'active');\nconst mapped = valid.map(item => ({\n  json: {\n    id: item.json.id,\n    name: item.json.name\n  }\n}));\n\nreturn mapped;\n```\n\n### Pattern 2: $input.first() - Very Common\n\n**Use when**: Working with single objects, API responses, first-in-first-out\n\n```javascript\n\u002F\u002F Get first item only\nconst firstItem = $input.first();\nconst data = firstItem.json;\n\nreturn [{\n  json: {\n    result: processData(data),\n    processedAt: new Date().toISOString()\n  }\n}];\n```\n\n### Pattern 3: $input.item - Each Item Mode Only\n\n**Use when**: In \"Run Once for Each Item\" mode\n\n```javascript\n\u002F\u002F Current item in loop (Each Item mode only)\nconst currentItem = $input.item;\n\nreturn [{\n  json: {\n    ...currentItem.json,\n    itemProcessed: true\n  }\n}];\n```\n\n### Pattern 4: $node - Reference Other Nodes\n\n**Use when**: Need data from specific nodes in workflow\n\n```javascript\n\u002F\u002F Get output from specific node\nconst webhookData = $node[\"Webhook\"].json;\nconst httpData = $node[\"HTTP Request\"].json;\n\nreturn [{\n  json: {\n    combined: {\n      webhook: webhookData,\n      api: httpData\n    }\n  }\n}];\n```\n\n**See**: DATA_ACCESS.md for comprehensive guide\n\n---\n\n## Critical: Webhook Data Structure\n\n**MOST COMMON MISTAKE**: Webhook data is nested under `.body`\n\n```javascript\n\u002F\u002F ❌ WRONG - Will return undefined\nconst name = $json.name;\nconst email = $json.email;\n\n\u002F\u002F ✅ CORRECT - Webhook data is under .body\nconst name = $json.body.name;\nconst email = $json.body.email;\n\n\u002F\u002F Or with $input\nconst webhookData = $input.first().json.body;\nconst name = webhookData.name;\n```\n\n**Why**: Webhook node wraps all request data under `body` property. This includes POST data, query parameters, and JSON payloads.\n\n**See**: DATA_ACCESS.md for full webhook structure details\n\n---\n\n## Return Format Requirements\n\n**CRITICAL RULE**: Always return array of objects with `json` property\n\n### Correct Return Formats\n\n```javascript\n\u002F\u002F ✅ Single result\nreturn [{\n  json: {\n    field1: value1,\n    field2: value2\n  }\n}];\n\n\u002F\u002F ✅ Multiple results\nreturn [\n  {json: {id: 1, data: 'first'}},\n  {json: {id: 2, data: 'second'}}\n];\n\n\u002F\u002F ✅ Transformed array\nconst transformed = $input.all()\n  .filter(item => item.json.valid)\n  .map(item => ({\n    json: {\n      id: item.json.id,\n      processed: true\n    }\n  }));\nreturn transformed;\n\n\u002F\u002F ✅ Empty result (when no data to return)\nreturn [];\n\n\u002F\u002F ✅ Conditional return\nif (shouldProcess) {\n  return [{json: processedData}];\n} else {\n  return [];\n}\n```\n\n### Incorrect Return Formats\n\n```javascript\n\u002F\u002F ❌ WRONG: Object without array wrapper\nreturn {\n  json: {field: value}\n};\n\n\u002F\u002F ❌ WRONG: Array without json wrapper\nreturn [{field: value}];\n\n\u002F\u002F ❌ WRONG: Plain string\nreturn \"processed\";\n\n\u002F\u002F ❌ WRONG: Raw data without mapping\nreturn $input.all();  \u002F\u002F Missing .map()\n\n\u002F\u002F ❌ WRONG: Incomplete structure\nreturn [{data: value}];  \u002F\u002F Should be {json: value}\n```\n\n**Why it matters**: Next nodes expect array format. Incorrect format causes workflow execution to fail.\n\n**See**: ERROR_PATTERNS.md #3 for detailed error solutions\n\n---\n\n## Common Patterns Overview\n\nBased on production workflows, here are the most useful patterns:\n\n### 1. Multi-Source Data Aggregation\nCombine data from multiple APIs, webhooks, or nodes\n\n```javascript\nconst allItems = $input.all();\nconst results = [];\n\nfor (const item of allItems) {\n  const sourceName = item.json.name || 'Unknown';\n  \u002F\u002F Parse source-specific structure\n  if (sourceName === 'API1' && item.json.data) {\n    results.push({\n      json: {\n        title: item.json.data.title,\n        source: 'API1'\n      }\n    });\n  }\n}\n\nreturn results;\n```\n\n### 2. Filtering with Regex\nExtract patterns, mentions, or keywords from text\n\n```javascript\nconst pattern = \u002F\\b([A-Z]{2,5})\\b\u002Fg;\nconst matches = {};\n\nfor (const item of $input.all()) {\n  const text = item.json.text;\n  const found = text.match(pattern);\n\n  if (found) {\n    found.forEach(match => {\n      matches[match] = (matches[match] || 0) + 1;\n    });\n  }\n}\n\nreturn [{json: {matches}}];\n```\n\n### 3. Data Transformation & Enrichment\nMap fields, normalize formats, add computed fields\n\n```javascript\nconst items = $input.all();\n\nreturn items.map(item => {\n  const data = item.json;\n  const nameParts = data.name.split(' ');\n\n  return {\n    json: {\n      first_name: nameParts[0],\n      last_name: nameParts.slice(1).join(' '),\n      email: data.email,\n      created_at: new Date().toISOString()\n    }\n  };\n});\n```\n\n### 4. Top N Filtering & Ranking\nSort and limit results\n\n```javascript\nconst items = $input.all();\n\nconst topItems = items\n  .sort((a, b) => (b.json.score || 0) - (a.json.score || 0))\n  .slice(0, 10);\n\nreturn topItems.map(item => ({json: item.json}));\n```\n\n### 5. Aggregation & Reporting\nSum, count, group data\n\n```javascript\nconst items = $input.all();\nconst total = items.reduce((sum, item) => sum + (item.json.amount || 0), 0);\n\nreturn [{\n  json: {\n    total,\n    count: items.length,\n    average: total \u002F items.length,\n    timestamp: new Date().toISOString()\n  }\n}];\n```\n\n**See**: COMMON_PATTERNS.md for 10 detailed production patterns\n\n---\n\n## Error Prevention - Top 5 Mistakes\n\n### #1: Empty Code or Missing Return (Most Common)\n\n```javascript\n\u002F\u002F ❌ WRONG: No return statement\nconst items = $input.all();\n\u002F\u002F ... processing code ...\n\u002F\u002F Forgot to return!\n\n\u002F\u002F ✅ CORRECT: Always return data\nconst items = $input.all();\n\u002F\u002F ... processing ...\nreturn items.map(item => ({json: item.json}));\n```\n\n### #2: Expression Syntax Confusion\n\n```javascript\n\u002F\u002F ❌ WRONG: Using n8n expression syntax in code\nconst value = \"{{ $json.field }}\";\n\n\u002F\u002F ✅ CORRECT: Use JavaScript template literals\nconst value = `${$json.field}`;\n\n\u002F\u002F ✅ CORRECT: Direct access\nconst value = $input.first().json.field;\n```\n\n### #3: Incorrect Return Wrapper\n\n```javascript\n\u002F\u002F ❌ WRONG: Returning object instead of array\nreturn {json: {result: 'success'}};\n\n\u002F\u002F ✅ CORRECT: Array wrapper required\nreturn [{json: {result: 'success'}}];\n```\n\n### #4: Missing Null Checks\n\n```javascript\n\u002F\u002F ❌ WRONG: Crashes if field doesn't exist\nconst value = item.json.user.email;\n\n\u002F\u002F ✅ CORRECT: Safe access with optional chaining\nconst value = item.json?.user?.email || 'no-email@example.com';\n\n\u002F\u002F ✅ CORRECT: Guard clause\nif (!item.json.user) {\n  return [];\n}\nconst value = item.json.user.email;\n```\n\n### #5: Webhook Body Nesting\n\n```javascript\n\u002F\u002F ❌ WRONG: Direct access to webhook data\nconst email = $json.email;\n\n\u002F\u002F ✅ CORRECT: Webhook data under .body\nconst email = $json.body.email;\n```\n\n**See**: ERROR_PATTERNS.md for comprehensive error guide\n\n---\n\n## Built-in Functions & Helpers\n\n### $helpers.httpRequest()\n\nMake HTTP requests from within code:\n\n```javascript\nconst response = await $helpers.httpRequest({\n  method: 'GET',\n  url: 'https:\u002F\u002Fapi.example.com\u002Fdata',\n  headers: {\n    'Authorization': 'Bearer token',\n    'Content-Type': 'application\u002Fjson'\n  }\n});\n\nreturn [{json: {data: response}}];\n```\n\n### DateTime (Luxon)\n\nDate and time operations:\n\n```javascript\n\u002F\u002F Current time\nconst now = DateTime.now();\n\n\u002F\u002F Format dates\nconst formatted = now.toFormat('yyyy-MM-dd');\nconst iso = now.toISO();\n\n\u002F\u002F Date arithmetic\nconst tomorrow = now.plus({days: 1});\nconst lastWeek = now.minus({weeks: 1});\n\nreturn [{\n  json: {\n    today: formatted,\n    tomorrow: tomorrow.toFormat('yyyy-MM-dd')\n  }\n}];\n```\n\n### $jmespath()\n\nQuery JSON structures:\n\n```javascript\nconst data = $input.first().json;\n\n\u002F\u002F Filter array\nconst adults = $jmespath(data, 'users[?age >= `18`]');\n\n\u002F\u002F Extract fields\nconst names = $jmespath(data, 'users[*].name');\n\nreturn [{json: {adults, names}}];\n```\n\n**See**: BUILTIN_FUNCTIONS.md for complete reference\n\n---\n\n## Best Practices\n\n### 1. Always Validate Input Data\n\n```javascript\nconst items = $input.all();\n\n\u002F\u002F Check if data exists\nif (!items || items.length === 0) {\n  return [];\n}\n\n\u002F\u002F Validate structure\nif (!items[0].json) {\n  return [{json: {error: 'Invalid input format'}}];\n}\n\n\u002F\u002F Continue processing...\n```\n\n### 2. Use Try-Catch for Error Handling\n\n```javascript\ntry {\n  const response = await $helpers.httpRequest({\n    url: 'https:\u002F\u002Fapi.example.com\u002Fdata'\n  });\n\n  return [{json: {success: true, data: response}}];\n} catch (error) {\n  return [{\n    json: {\n      success: false,\n      error: error.message\n    }\n  }];\n}\n```\n\n### 3. Prefer Array Methods Over Loops\n\n```javascript\n\u002F\u002F ✅ GOOD: Functional approach\nconst processed = $input.all()\n  .filter(item => item.json.valid)\n  .map(item => ({json: {id: item.json.id}}));\n\n\u002F\u002F ❌ SLOWER: Manual loop\nconst processed = [];\nfor (const item of $input.all()) {\n  if (item.json.valid) {\n    processed.push({json: {id: item.json.id}});\n  }\n}\n```\n\n### 4. Filter Early, Process Late\n\n```javascript\n\u002F\u002F ✅ GOOD: Filter first to reduce processing\nconst processed = $input.all()\n  .filter(item => item.json.status === 'active')  \u002F\u002F Reduce dataset first\n  .map(item => expensiveTransformation(item));  \u002F\u002F Then transform\n\n\u002F\u002F ❌ WASTEFUL: Transform everything, then filter\nconst processed = $input.all()\n  .map(item => expensiveTransformation(item))  \u002F\u002F Wastes CPU\n  .filter(item => item.json.status === 'active');\n```\n\n### 5. Use Descriptive Variable Names\n\n```javascript\n\u002F\u002F ✅ GOOD: Clear intent\nconst activeUsers = $input.all().filter(item => item.json.active);\nconst totalRevenue = activeUsers.reduce((sum, user) => sum + user.json.revenue, 0);\n\n\u002F\u002F ❌ BAD: Unclear purpose\nconst a = $input.all().filter(item => item.json.active);\nconst t = a.reduce((s, u) => s + u.json.revenue, 0);\n```\n\n### 6. Debug with console.log()\n\n```javascript\n\u002F\u002F Debug statements appear in browser console\nconst items = $input.all();\nconsole.log(`Processing ${items.length} items`);\n\nfor (const item of items) {\n  console.log('Item data:', item.json);\n  \u002F\u002F Process...\n}\n\nreturn result;\n```\n\n---\n\n## When to Use Code Node\n\nUse Code node when:\n- ✅ Complex transformations requiring multiple steps\n- ✅ Custom calculations or business logic\n- ✅ Recursive operations\n- ✅ API response parsing with complex structure\n- ✅ Multi-step conditionals\n- ✅ Data aggregation across items\n\nConsider other nodes when:\n- ❌ Simple field mapping → Use **Set** node\n- ❌ Basic filtering → Use **Filter** node\n- ❌ Simple conditionals → Use **IF** or **Switch** node\n- ❌ HTTP requests only → Use **HTTP Request** node\n\n**Code node excels at**: Complex logic that would require chaining many simple nodes\n\n---\n\n## Integration with Other Skills\n\n### Works With:\n\n**n8n Expression Syntax**:\n- Expressions use `{{ }}` syntax in other nodes\n- Code nodes use JavaScript directly (no `{{ }}`)\n- When to use expressions vs code\n\n**n8n MCP Tools Expert**:\n- How to find Code node: `search_nodes({query: \"code\"})`\n- Get configuration help: `get_node_essentials(\"nodes-base.code\")`\n- Validate code: `validate_node_operation()`\n\n**n8n Node Configuration**:\n- Mode selection (All Items vs Each Item)\n- Language selection (JavaScript vs Python)\n- Understanding property dependencies\n\n**n8n Workflow Patterns**:\n- Code nodes in transformation step\n- Webhook → Code → API pattern\n- Error handling in workflows\n\n**n8n Validation Expert**:\n- Validate Code node configuration\n- Handle validation errors\n- Auto-fix common issues\n\n---\n\n## Quick Reference Checklist\n\nBefore deploying Code nodes, verify:\n\n- [ ] **Code is not empty** - Must have meaningful logic\n- [ ] **Return statement exists** - Must return array of objects\n- [ ] **Proper return format** - Each item: `{json: {...}}`\n- [ ] **Data access correct** - Using `$input.all()`, `$input.first()`, or `$input.item`\n- [ ] **No n8n expressions** - Use JavaScript template literals: `` `${value}` ``\n- [ ] **Error handling** - Guard clauses for null\u002Fundefined inputs\n- [ ] **Webhook data** - Access via `.body` if from webhook\n- [ ] **Mode selection** - \"All Items\" for most cases\n- [ ] **Performance** - Prefer map\u002Ffilter over manual loops\n- [ ] **Output consistent** - All code paths return same structure\n\n---\n\n## Additional Resources\n\n### Related Files\n- DATA_ACCESS.md - Comprehensive data access patterns\n- COMMON_PATTERNS.md - 10 production-tested patterns\n- ERROR_PATTERNS.md - Top 5 errors and solutions\n- BUILTIN_FUNCTIONS.md - Complete built-in reference\n\n### n8n Documentation\n- Code Node Guide: https:\u002F\u002Fdocs.n8n.io\u002Fcode\u002Fcode-node\u002F\n- Built-in Methods: https:\u002F\u002Fdocs.n8n.io\u002Fcode-examples\u002Fmethods-variables-reference\u002F\n- Luxon Documentation: https:\u002F\u002Fmoment.github.io\u002Fluxon\u002F\n\n---\n\n**Ready to write JavaScript in n8n Code nodes!** Start with simple transformations, use the error patterns guide to avoid common mistakes, and reference the pattern library for production-ready examples.\n\n## Limitations\n- Use this skill only when the task clearly matches the scope described above.\n- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.\n- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.\n","","imported","https:\u002F\u002Fgithub.com\u002Fsickn33\u002Fantigravity-awesome-skills","user_system_seed","SkillOPIC",true,135,1805,"2026-05-16 13:30:07",{"id":8,"name":21,"slug":22,"icon":23,"description":24,"sort":25,"createdAt":26},"编程开发","coding","mdi-code-braces","代码生成、调试、审查，提升开发效率",2,"2026-05-16 12:53:40",{"id":7,"name":28,"slug":29,"icon":30,"description":31,"moduleId":8,"sort":25,"skillCount":32,"createdAt":26},"后端开发","backend","mdi-server","API、数据库、服务端架构",296,[34],{"id":35,"skillId":4,"version":36,"fileName":37,"fileSize":38,"filePath":39,"fileHash":40,"manifest":41,"createdAt":19},"61e3eb78-1c5b-4cf6-a96a-7ce0d95c6e6a","1.0.0","n8n-code-javascript.zip",5781,"uploads\u002Fskills\u002F10f1b7be-eacc-4e3e-a215-55510f8340a4\u002Fn8n-code-javascript.zip","479be81ea438427a7ad4726adeb7cf263b774a4db465179a844f163fda40b3de","[{\"path\":\"SKILL.md\",\"isDirectory\":false,\"size\":16252}]",{"code":43,"message":44,"data":45},200,"success",{"items":46,"stats":47,"page":50},[],{"averageRating":48,"totalRatings":48,"ratingCounts":49},0,[48,48,48,48,48],{"limit":51,"offset":48,"hasMore":52,"nextOffset":51,"ratedOnly":16},15,false]