[ PROMPT_NODE_28082 ]
N8n Code Javascript 常用模式
[ SKILL_DOCUMENTATION ]
# 常见模式 - JavaScript 代码节点
生产环境验证过的 n8n 代码节点模式。这些模式已在实际工作流中得到验证。
---
## 概述
本指南涵盖了 n8n 工作流中最有用的 10 个代码节点模式。每个模式包含:
- **使用场景**:何时使用此模式
- **关键技术**:演示的重要编码技术
- **完整示例**:可直接适配的可运行代码
- **变体**:常见修改方式
**模式分类:**
- 数据聚合 (模式 1, 5, 10)
- 内容处理 (模式 2, 3)
- 数据验证与比较 (模式 4)
- 数据转换 (模式 5, 6, 7)
- 输出格式化 (模式 8)
- 过滤与排序 (模式 9)
---
## 模式 1:多源数据聚合
**使用场景**:合并来自多个 API、RSS 源、Webhook 或数据库的数据
**何时使用:**
- 从多个服务收集数据
- 规范化不同的 API 响应格式
- 将数据源合并为统一结构
- 构建聚合报告
**关键技术**:循环迭代、条件解析、数据规范化
### 完整示例
javascript
// 处理并结构化从多个来源收集的数据
const allItems = $input.all();
let processedArticles = [];
// 处理不同的源格式
for (const item of allItems) {
const sourceName = item.json.name || 'Unknown';
const sourceData = item.json;
// 解析特定源结构 - Hacker News 格式
if (sourceName === 'Hacker News' && sourceData.hits) {
for (const hit of sourceData.hits) {
processedArticles.push({
title: hit.title,
url: hit.url,
summary: hit.story_text || 'No summary',
source: 'Hacker News',
score: hit.points || 0,
fetchedAt: new Date().toISOString()
});
}
}
// 解析特定源结构 - Reddit 格式
else if (sourceName === 'Reddit' && sourceData.data?.children) {
for (const post of sourceData.data.children) {
processedArticles.push({
title: post.data.title,
url: post.data.url,
summary: post.data.selftext || 'No summary',
source: 'Reddit',
score: post.data.score || 0,
fetchedAt: new Date().toISOString()
});
}
}
// 解析特定源结构 - RSS 订阅格式
else if (sourceName === 'RSS' && sourceData.items) {
for (const rssItem of sourceData.items) {
processedArticles.push({
title: rssItem.title,
url: rssItem.link,