D: 🚀 n8n의 강력한 Code Node로 워크플로우의 한계를 뛰어넘어보세요! 개발자와 비개발자 모두 쉽게 사용할 수 있는 JavaScript/Python 코드 활용법을 10가지 실제 사례와 함께 상세히 소개합니다.
1. Code Node 기본 이해
// 기본 구조 예시
return {
json: {
message: "Hello World!",
timestamp: new Date().toISOString()
}
};
- 동적 데이터 생성 ⏰: 실시간 타임스탬프 추가
- 데이터 변환 🔄: JSON 형식으로 자유롭게 가공
- 외부 라이브러리 📚: Lodash, Moment.js 등 활용 가능
2. 실전 예시 10선 (JavaScript 기준)
① 이메일 자동 분류기
const keywordMap = {
"지원": "recruitment",
"문의": "inquiry",
"불만": "complaint"
};
let category = "general";
Object.keys(keywordMap).forEach(key => {
if (input.json.emailContent.includes(key)) {
category = keywordMap[key];
}
});
return { json: { ...input.json, category } };
- 📧 제목/본문 분석 → 자동 라벨링
② 주식 알림 시스템
const threshold = 150000;
const currentPrice = input.json.kospi;
return {
json: {
alert: currentPrice > threshold
? "📈 매도 신호!"
: "📉 관망 필요",
price: currentPrice
}
};
③ 날씨 기반 추천
const weather = input.json.weather;
let recommendation = "";
switch(true) {
case weather.temp > 30:
recommendation = "🧊 아이스 아메리카노 추천!";
break;
case weather.rain > 50:
recommendation = "☔ 우산 챙기세요!";
break;
default:
recommendation = "🌞 산책하기 좋은 날씨!";
}
return { json: { ...weather, recommendation } };
④ 다국어 번역기
const translations = {
en: { hello: "Hello", goodbye: "Goodbye" },
ko: { hello: "안녕하세요", goodbye: "안녕히 가세요" }
};
const lang = input.json.language || 'en';
return {
json: {
original: input.json.text,
translated: translations[lang][input.json.text]
}
};
⑤ 이미지 메타데이터 처리
const sharp = require('sharp');
const meta = await sharp(input.json.imageBuffer)
.metadata();
return {
json: {
width: meta.width,
height: meta.height,
format: meta.format
}
};
⑥ 주문 자동 할인
const order = input.json;
let discount = 0;
if (order.items.length > 5) discount += 0.1;
if (order.customerLevel === 'vip') discount += 0.15;
return {
json: {
...order,
finalPrice: order.total * (1 - Math.min(discount, 0.25))
}
};
⑦ 소셜 미디어 분석
const posts = input.json.posts;
const analysis = posts.reduce((acc, post) => {
acc.totalLikes += post.likes;
acc.averageLength += post.content.length / posts.length;
return acc;
}, { totalLikes: 0, averageLength: 0 });
return { json: analysis };
⑧ IoT 데이터 필터링
// 5분 평균 온도 계산
const readings = input.json.sensorData;
const valid = readings.filter(r => r.temp > -20 && r.temp s + r.temp, 0) / valid.length,
anomalyCount: readings.length - valid.length
}
};
⑨ 자동화된 보고서 생성
const data = input.json;
const report = `
# 📊 ${new Date().toLocaleDateString()} 리포트
- 총 매출: ${data.sales.toLocaleString()}원
- TOP 제품: ${data.topProduct.name} (${data.topProduct.ratio}%)
`;
return {
json: {
...data,
markdownReport: report
}
};
⑩ 보안 강화 파이프라인
const crypto = require('crypto');
const hash = crypto.createHash('sha256')
.update(input.json.password)
.digest('hex');
return {
json: {
...input.json,
password: hash,
originalLength: input.json.password.length
}
};
3. 고급 활용 팁 💡
-
에러 핸들링: try-catch 블록으로 안정성 향상
try { // 실행 코드 } catch (e) { return { json: { error: e.message, stack: e.stack } }; }
-
비동기 처리: async/await 지원
const fetch = require('node-fetch'); const response = await fetch('https://api.example.com');
-
디버깅: console.log 출력은 Execution Log에서 확인
-
성능 최적화:
- 무거운 연산은 외부 API로 분리
- 반복문 대신 map/filter 사용
4. 결론
n8n의 Code Node는 👨💻 개발자의 강력한 도구이면서도, 간단한 스크립팅으로 🧑💼 비개발자도 쉽게 접근할 수 있는 매력적인 기능입니다. 오늘 소개한 10가지 예시를 시작으로 여러분의 워크플로우에 무한한 가능성을 더해보세요!
💬 실제 적용 사례나 궁금한 점이 있다면 댓글로 공유해주세요. 함께 더 나은 자동화 솔루션을 만들어가요!