n8n-code-javascript について
n8n-code-javascript は、n8n の Code ノードで JavaScript を書くための実践的なスキルです。実行モード、データ参照、戻り値の形式、組み込みヘルパー、一般的なワークフローパターンを解説します。
主な機能
- 01適切な実行モードの選択
- 02入力や他ノードのデータ参照
- 03指定形式でのアイテム返却
- 04HTTP・日付・JSON ヘルパーの利用
- 05集約と変換のパターン適用
- 06よくあるコードエラーの予防
活用シーン
- 01ワークフロー内のアイテム集約や変換
- 02Webhook リクエストデータの解析
- 03Code ノードからの HTTP リクエスト
- 04Code ノード出力の検証と問題調査
インストール
コマンドをコピーしてターミナルで実行します。
npx skills add https:/ / github.com/ ovachiever/ droid-tings --skill n8n-code-javascriptインストール後、Claude Code で/n8n-code-javascriptを入力して読み込まれたか確認します。
同梱ファイル
SKILL.md と一緒にインストールされる参考資料やスクリプト。
BUILTIN_FUNCTIONS.mdCOMMON_PATTERNS.mdDATA_ACCESS.mdERROR_PATTERNS.mdREADME.md詳細
JavaScript コードノード
n8n の Code ノードで JavaScript コードを書くための専門的なガイダンスです。
クイックスタート
// Basic template for Code nodes
const items = $input.all();
// Process data
const processed = items.map(item => ({
json: {
...item.json,
processed: true,
timestamp: new Date().toISOString()
}
}));
return processed;
基本ルール
- 「Run Once for All Items」モードを選択します(ほとんどのユースケースで推奨)
- データにアクセスします:
$input.all()、$input.first()、または$input.item - 重要:
[{json: {...}}]形式で返す必要があります - 重要:Webhook データは
$json直下ではなく、$json.bodyにあります - 組み込み機能を利用できます:$helpers.httpRequest()、DateTime(Luxon)、$jmespath()
モード選択ガイド
Code ノードには 2 つの実行モードがあります。ユースケースに合わせて選択してください。
Run Once for All Items(推奨・デフォルト)
このモードを使うケース: ユースケースの 95%
- 仕組み:入力数にかかわらず、コードは1 回実行されます
- データアクセス:
$input.all()またはitems配列 - 最適な用途:集約、フィルタリング、バッチ処理、変換、すべてのデータを使った API 呼び出し
- パフォーマンス:複数アイテムの場合に高速(実行は 1 回)
// Example: Calculate total from all items
const allItems = $input.all();
const total = allItems.reduce((sum, item) => sum + (item.json.amount || 0), 0);
return [{
json: {
total,
count: allItems.length,
average: total / allItems.length
}
}];
使用するケース:
- ✅ データセット内の複数のアイテムを比較する
- ✅ 合計、平均、または統計値を計算する
- ✅ アイテムを並べ替えたり、順位付けしたりする
- ✅ 重複を排除する
- ✅ 集約レポートを作成する
- ✅ 複数のアイテムのデータを結合する
Run Once for Each Item
このモードを使うケース: 特殊なケースのみ
- 仕組み:コードは各入力アイテムに対して個別に実行されます
- データアクセス:
$input.itemまたは$item - 最適な用途:アイテムごとのロジック、個別の処理、アイテムごとの検証
- パフォーマンス:大規模なデータセットでは低速(複数回実行)
// Example: Add processing timestamp to each item
const item = $input.item;
return [{
json: {
...item.json,
processed: true,
processedAt: new Date().toISOString()
}
}];
使用するケース:
- ✅ 各アイテムで個別に API を呼び出す必要がある
- ✅ アイテムごとに異なるエラー処理を行って検証する
- ✅ アイテムのプロパティに応じて、アイテムごとに変換する
- ✅ ビジネスロジック上、アイテムを個別に処理する必要がある
選択の目安:
- 複数のアイテムを確認する必要がありますか? → 「All Items」モードを使います
- 各アイテムは完全に独立していますか? → 「Each Item」モードを使います
- 判断がつきませんか? → 「All Items」モードを使います(必要に応じて内部でループできます)
データアクセスパターン
パターン 1:$input.all() - 最も一般的
使用するケース:配列の処理、バッチ処理、集約
// Get all items from previous node
const allItems = $input.all();
// Filter, map, reduce as needed
const valid = allItems.filter(item => item.json.status === 'active');
const mapped = valid.map(item => ({
json: {
id: item.json.id,
name: item.json.name
}
}));
return mapped;
パターン 2:$input.first() - 非常によく使われる
使用するケース:単一オブジェクト、API レスポンス、先入れ先出しのデータを扱う
// Get first item only
const firstItem = $input.first();
const data = firstItem.json;
return [{
json: {
result: processData(data),
processedAt: new Date().toISOString()
}
}];
パターン 3:$input.item - Each Item モードのみ
使用するケース:「Run Once for Each Item」モード
// Current item in loop (Each Item mode only)
const currentItem = $input.item;
return [{
json: {
...currentItem.json,
itemProcessed: true
}
}];
パターン 4:$node - 他のノードを参照
使用するケース:ワークフロー内の特定のノードからデータを取得する
// Get output from specific node
const webhookData = $node["Webhook"].json;
const httpData = $node["HTTP Request"].json;
return [{
json: {
combined: {
webhook: webhookData,
api: httpData
}
}
}];
参照先:DATA_ACCESS.md(詳細なガイド)
重要:Webhook のデータ構造
最もよくある間違い:Webhook データは .body の下にネストされています
// ❌ WRONG - Will return undefined
const name = $json.name;
const email = $json.email;
// ✅ CORRECT - Webhook data is under .body
const name = $json.body.name;
const email = $json.body.email;
// Or with $input
const webhookData = $input.first().json.body;
const name = webhookData.name;
理由:Webhook ノードは、すべてのリクエストデータを body プロパティの下に格納します。これには POST データ、クエリパラメーター、JSON ペイロードが含まれます。
参照先:DATA_ACCESS.md(Webhook のデータ構造の詳細)
戻り値の形式の要件
重要なルール:必ず json プロパティを持つオブジェクトの配列を返します
正しい戻り値の形式
// ✅ Single result
return [{
json: {
field1: value1,
field2: value2
}
}];
// ✅ Multiple results
return [
{json: {id: 1, data: 'first'}},
{json: {id: 2, data: 'second'}}
];
// ✅ Transformed array
const transformed = $input.all()
.filter(item => item.json.valid)
.map(item => ({
json: {
id: item.json.id,
processed: true
}
}));
return transformed;
// ✅ Empty result (when no data to return)
return [];
// ✅ Conditional return
if (shouldProcess) {
return [{json: processedData}];
} else {
return [];
}
誤った戻り値の形式
// ❌ WRONG: Object without array wrapper
return {
json: {field: value}
};
// ❌ WRONG: Array without json wrapper
return [{field: value}];
// ❌ WRONG: Plain string
return "processed";
// ❌ WRONG: Raw data without mapping
return $input.all(); // Missing .map()
// ❌ WRONG: Incomplete structure
return [{data: value}]; // Should be {json: value}
重要な理由:後続のノードは配列形式を想定しています。形式が正しくないと、ワークフローの実行に失敗します。
参照先:ERROR_PATTERNS.md #3(エラーの詳しい解決方法)
よく使われるパターンの概要
本番環境のワークフローをもとに、特に便利なパターンを紹介します。
1. 複数ソースのデータ集約
複数の API、Webhook、またはノードのデータを結合します
const allItems = $input.all();
const results = [];
for (const item of allItems) {
const sourceName = item.json.name || 'Unknown';
// Parse source-specific structure
if (sourceName === 'API1' && item.json.data) {
results.push({
json: {
title: item.json.data.title,
source: 'API1'
}
});
}
}
return results;
2. 正規表現によるフィルタリング
テキストからパターン、メンション、またはキーワードを抽出します
const pattern = /\b([A-Z]{2,5})\b/g;
const matches = {};
for (const item of $input.all()) {
const text = item.json.text;
const found = text.match(pattern);
if (found) {
found.forEach(match => {
matches[match] = (matches[match] || 0) + 1;
});
}
}
return [{json: {matches}}];
3. データの変換と拡充
フィールドのマッピング、形式の正規化、計算フィールドの追加を行います
const items = $input.all();
return items.map(item => {
const data = item.json;
const nameParts = data.name.split(' ');
return {
json: {
first_name: nameParts[0],
last_name: nameParts.slice(1).join(' '),
email: data.email,
created_at: new Date().toISOString()
}
};
});
4. 上位 N 件のフィルタリングと順位付け
結果を並べ替えて件数を制限します
const items = $input.all();
const topItems = items
.sort((a, b) => (b.json.score || 0) - (a.json.score || 0))
.slice(0, 10);
return topItems.map(item => ({json: item.json}));
5. 集約とレポート作成
データの合計、カウント、グループ化を行います
const items = $input.all();
const total = items.reduce((sum, item) => sum + (item.json.amount || 0), 0);
return [{
json: {
total,
count: items.length,
average: total / items.length,
timestamp: new Date().toISOString()
}
}];
参照先:COMMON_PATTERNS.md(本番環境で使える 10 種類のパターンを詳しく解説)
エラーの防止 - よくある間違いトップ 5
#1:コードが空、または return がない(最もよくある)
// ❌ WRONG: No return statement
const items = $input.all();
// ... processing code ...
// Forgot to return!
// ✅ CORRECT: Always return data
const items = $input.all();
// ... processing ...
return items.map(item => ({json: item.json}));
#2:式構文の混乱
// ❌ WRONG: Using n8n expression syntax in code
const value = "{{ $json.field }}";
// ✅ CORRECT: Use JavaScript template literals
const value = `${$json.field}`;
// ✅ CORRECT: Direct access
const value = $input.first().json.field;
#3:戻り値のラッパーが不正
// ❌ WRONG: Returning object instead of array
return {json: {result: 'success'}};
// ✅ CORRECT: Array wrapper required
return [{json: {result: 'success'}}];
#4:Null チェックの不足
// ❌ WRONG: Crashes if field doesn't exist
const value = item.json.user.email;
// ✅ CORRECT: Safe access with optional chaining
const value = item.json?.user?.email || '[email protected]';
// ✅ CORRECT: Guard clause
if (!item.json.user) {
return [];
}
const value = item.json.user.email;
#5:Webhook の本文のネスト
// ❌ WRONG: Direct access to webhook data
const email = $json.email;
// ✅ CORRECT: Webhook data under .body
const email = $json.body.email;
参照:ERROR_PATTERNS.mdで包括的なエラーガイドを確認できます
組み込み関数とヘルパー
$helpers.httpRequest()
コード内から HTTP リクエストを送信します:
const response = await $helpers.httpRequest({
method: 'GET',
url: 'https://api.example.com/data',
headers: {
'Authorization': 'Bearer token',
'Content-Type': 'application/json'
}
});
return [{json: {data: response}}];
DateTime(Luxon)
日時の操作:
// Current time
const now = DateTime.now();
// Format dates
const formatted = now.toFormat('yyyy-MM-dd');
const iso = now.toISO();
// Date arithmetic
const tomorrow = now.plus({days: 1});
const lastWeek = now.minus({weeks: 1});
return [{
json: {
today: formatted,
tomorrow: tomorrow.toFormat('yyyy-MM-dd')
}
}];
$jmespath()
JSON 構造をクエリします:
const data = $input.first().json;
// Filter array
const adults = $jmespath(data, 'users[?age >= `18`]');
// Extract fields
const names = $jmespath(data, 'users[*].name');
return [{json: {adults, names}}];
参照:BUILTIN_FUNCTIONS.mdで完全なリファレンスを確認できます
ベストプラクティス
1. 入力データは必ず検証する
const items = $input.all();
// Check if data exists
if (!items || items.length === 0) {
return [];
}
// Validate structure
if (!items[0].json) {
return [{json: {error: 'Invalid input format'}}];
}
// Continue processing...
2. エラー処理には Try-Catch を使う
try {
const response = await $helpers.httpRequest({
url: 'https://api.example.com/data'
});
return [{json: {success: true, data: response}}];
} catch (error) {
return [{
json: {
success: false,
error: error.message
}
}];
}
3. ループより配列メソッドを優先する
// ✅ GOOD: Functional approach
const processed = $input.all()
.filter(item => item.json.valid)
.map(item => ({json: {id: item.json.id}}));
// ❌ SLOWER: Manual loop
const processed = [];
for (const item of $input.all()) {
if (item.json.valid) {
processed.push({json: {id: item.json.id}});
}
}
4. 早めにフィルタリングし、処理は後で行う
// ✅ GOOD: Filter first to reduce processing
const processed = $input.all()
.filter(item => item.json.status === 'active') // Reduce dataset first
.map(item => expensiveTransformation(item)); // Then transform
// ❌ WASTEFUL: Transform everything, then filter
const processed = $input.all()
.map(item => expensiveTransformation(item)) // Wastes CPU
.filter(item => item.json.status === 'active');
5. 説明的な変数名を使う
// ✅ GOOD: Clear intent
const activeUsers = $input.all().filter(item => item.json.active);
const totalRevenue = activeUsers.reduce((sum, user) => sum + user.json.revenue, 0);
// ❌ BAD: Unclear purpose
const a = $input.all().filter(item => item.json.active);
const t = a.reduce((s, u) => s + u.json.revenue, 0);
6. console.log() でデバッグする
// Debug statements appear in browser console
const items = $input.all();
console.log(`Processing ${items.length} items`);
for (const item of items) {
console.log('Item data:', item.json);
// Process...
}
return result;
Code ノードを使う場面
次のような場合は Code ノードを使います:
- ✅ 複数の手順が必要な複雑な変換
- ✅ カスタム計算やビジネスロジック
- ✅ 再帰的な操作
- ✅ 複雑な構造の API レスポンスの解析
- ✅ 複数段階の条件分岐
- ✅ アイテム間のデータ集約
次のような場合は、ほかのノードを検討してください:
- ❌ 単純なフィールドのマッピング → Set ノードを使います
- ❌ 基本的なフィルタリング → Filter ノードを使います
- ❌ 単純な条件分岐 → IF または Switch ノードを使います
- ❌ HTTP リクエストのみ → HTTP Request ノードを使います
Code ノードが得意とする処理:単純なノードを多数連結する必要がある複雑なロジック
ほかのスキルとの連携
連携するもの:
n8n Expression Syntax:
- ほかのノードでは
{{ }}構文を使います - Code ノードでは JavaScript を直接使います(
{{ }}は使いません) - 式とコードを使い分ける場面
n8n MCP Tools Expert:
- Code ノードを見つける方法:
search_nodes({query: "code"}) - 設定方法を確認する:
get_node_essentials("nodes-base.code") - コードを検証する:
validate_node_operation()
n8n Node Configuration:
- モードの選択(All Items と Each Item)
- 言語の選択(JavaScript と Python)
- プロパティの依存関係の理解
n8n Workflow Patterns:
- 変換ステップでの Code ノード
- Webhook → Code → API のパターン
- ワークフローでのエラー処理
n8n Validation Expert:
- Code ノードの設定を検証する
- 検証エラーに対処する
- よくある問題を自動修正する
クイックリファレンスチェックリスト
Code ノードをデプロイする前に、次の項目を確認してください:
- コードが空でない - 意味のあるロジックが必要です
- return 文がある - オブジェクトの配列を返す必要があります
- 戻り値の形式が正しい - 各アイテムは
{json: {...}}の形式です - データへのアクセスが正しい -
$input.all()、$input.first()、または$input.itemを使っています - n8n 式を使っていない - JavaScript のテンプレートリテラルを使います:
`${value}` - エラー処理がある - null/undefined の入力に対するガード節があります
- Webhook のデータ - Webhook からのデータには
.body経由でアクセスします - モードの選択 - ほとんどの場合は「All Items」を使います
- パフォーマンス - 手動ループより map/filter を優先します
- 出力に一貫性がある - すべてのコードパスで同じ構造を返します
追加リソース
関連ファイル
- DATA_ACCESS.md - データアクセスパターンの包括的なガイド
- COMMON_PATTERNS.md - 本番環境でテスト済みの 10 個のパターン
- ERROR_PATTERNS.md - よくある上位 5 件のエラーと解決策
- BUILTIN_FUNCTIONS.md - 組み込み機能の完全なリファレンス
n8n のドキュメント
- Code Node Guide: https://docs.n8n.io/code/code-node/
- Built-in Methods: https://docs.n8n.io/code-examples/methods-variables-reference/
- Luxon Documentation: https://moment.github.io/luxon/
n8n Code ノードで JavaScript を書く準備ができました! まずは簡単な変換から始め、よくある間違いを避けるためにエラーパターンガイドを活用し、本番環境向けの例についてはパターンライブラリを参照してください。