context系変数は、ChangeノードのGUI操作と Functionノード内のJavaScript のどちらでも読み書きできます。目的と好みに応じて使い分けましょう。
// Functionノード内のコード例
// 現在の flow.counter を取得し、+1 して保存
let count = flow.get('counter') || 0;
count += 1;
flow.set('counter', count);
// 取得した値を msg.payload に入れて次のノードに渡す
msg.payload = count;
return msg;
ここでは、context系変数がよく使われる場面を、実際にNode-REDにインポートして動かせるフロー付きで紹介します。各例のサンプルフローをコピーしてエディターに読み込み、手を動かしながら動作を確認してみてください。
例1: flow変数で「ボタン押下回数」をカウントする
よくある場面: 同じタブ内で「実行回数を数える」「前回の値を保持する」「2つのボタン(カウント/リセット)で同じ変数を操作する」など。
この例では、同じ処理を2つの方法で実装したフローを用意しています。Functionノードが難しく感じる方は、まずパターンB(Changeノードだけで実装)から試してください。動作結果はどちらも同じです。
パターンA: Functionノードを使う方法
Functionノードの中でJavaScriptを書き、flow.get() / flow.set() で flow変数を読み書きする方法です。JavaScriptに慣れていると、こちらのほうが短く書けます。
フロー構成:
カウント
→
カウント+1
→
表示
リセット
→
flow.counter=0
→
表示
Functionノードのコード:
let count = flow.get('counter') || 0;
count += 1;
flow.set('counter', count);
msg.payload = `カウント: ${count}回`;
return msg;
📋 パターンA サンプルフロー(Function版)
[
{
"id": "tab_flow_ex1a",
"type": "tab",
"label": "flow変数カウンター(Function版)",
"disabled": false,
"info": "",
"env": []
},
{
"id": "ex1a_inject_count",
"type": "inject",
"z": "tab_flow_ex1a",
"name": "カウント",
"props": [{"p": "payload"}],
"repeat": "",
"crontab": "",
"once": false,
"onceDelay": 0.1,
"topic": "",
"payload": "",
"payloadType": "date",
"x": 120,
"y": 100,
"wires": [["ex1a_func_count"]]
},
{
"id": "ex1a_func_count",
"type": "function",
"z": "tab_flow_ex1a",
"name": "カウント+1",
"func": "let count = flow.get('counter') || 0;\ncount += 1;\nflow.set('counter', count);\nmsg.payload = `カウント: ${count}回`;\nreturn msg;",
"outputs": 1,
"timeout": 0,
"noerr": 0,
"initialize": "",
"finalize": "",
"libs": [],
"x": 310,
"y": 100,
"wires": [["ex1a_debug"]]
},
{
"id": "ex1a_inject_reset",
"type": "inject",
"z": "tab_flow_ex1a",
"name": "リセット",
"props": [{"p": "payload"}],
"repeat": "",
"crontab": "",
"once": false,
"onceDelay": 0.1,
"topic": "",
"payload": "",
"payloadType": "date",
"x": 120,
"y": 180,
"wires": [["ex1a_change_reset"]]
},
{
"id": "ex1a_change_reset",
"type": "change",
"z": "tab_flow_ex1a",
"name": "カウンターを0に",
"rules": [
{"t": "set", "p": "counter", "pt": "flow", "to": "0", "tot": "num"},
{"t": "set", "p": "payload", "pt": "msg", "to": "リセットしました", "tot": "str"}
],
"x": 320,
"y": 180,
"wires": [["ex1a_debug"]]
},
{
"id": "ex1a_debug",
"type": "debug",
"z": "tab_flow_ex1a",
"name": "表示",
"active": true,
"tosidebar": true,
"console": false,
"tostatus": false,
"complete": "payload",
"targetType": "msg",
"x": 510,
"y": 140,
"wires": []
}
]
パターンB: Changeノードだけで実現する方法(JavaScript不要)
Functionノードを使わず、Changeノード1つで 同じ処理を実現できます。JSONata式を使って「flow.counter を取り出して +1 した値を、再び flow.counter に保存」します。JavaScriptを書かなくてよいので、プログラミング初心者に優しい方法です。
フロー構成:
カウント
→
+1して保存
→
表示
リセット
→
flow.counter=0
→
表示
Changeノード「+1して保存」の設定(2ルール):
ルール1: flow.counter を JSONata式 に設定
式: ($flowContext("counter") ? $flowContext("counter") : 0) + 1
(解説: 現在値が存在すればその値、無ければ0 として +1 し、flow.counter に書き戻す)
ルール2: msg.payload を JSONata式 に設定
式: "カウント: " & $flowContext("counter") & "回"
(解説: ルール1で更新済みの flow.counter を読んで文字列連結)
Changeノード版の仕組み:
- ルールは上から順に実行される
- ルール1で flow.counter を更新 → ルール2で更新後の値を使える
$flowContext("counter") はChangeノード内でも使える JSONata関数
& は JSONata の文字列連結演算子(JavaScriptの + に相当)
📋 パターンB サンプルフロー(Changeのみ版)
[
{
"id": "tab_flow_ex1b",
"type": "tab",
"label": "flow変数カウンター(Change版)",
"disabled": false,
"info": "",
"env": []
},
{
"id": "ex1b_inject_count",
"type": "inject",
"z": "tab_flow_ex1b",
"name": "カウント",
"props": [{"p": "payload"}],
"repeat": "",
"crontab": "",
"once": false,
"onceDelay": 0.1,
"topic": "",
"payload": "",
"payloadType": "date",
"x": 120,
"y": 100,
"wires": [["ex1b_change_count"]]
},
{
"id": "ex1b_change_count",
"type": "change",
"z": "tab_flow_ex1b",
"name": "+1して保存",
"rules": [
{"t": "set", "p": "counter", "pt": "flow", "to": "($flowContext(\"counter\") ? $flowContext(\"counter\") : 0) + 1", "tot": "jsonata"},
{"t": "set", "p": "payload", "pt": "msg", "to": "\"カウント: \" & $flowContext(\"counter\") & \"回\"", "tot": "jsonata"}
],
"x": 320,
"y": 100,
"wires": [["ex1b_debug"]]
},
{
"id": "ex1b_inject_reset",
"type": "inject",
"z": "tab_flow_ex1b",
"name": "リセット",
"props": [{"p": "payload"}],
"repeat": "",
"crontab": "",
"once": false,
"onceDelay": 0.1,
"topic": "",
"payload": "",
"payloadType": "date",
"x": 120,
"y": 180,
"wires": [["ex1b_change_reset"]]
},
{
"id": "ex1b_change_reset",
"type": "change",
"z": "tab_flow_ex1b",
"name": "カウンターを0に",
"rules": [
{"t": "set", "p": "counter", "pt": "flow", "to": "0", "tot": "num"},
{"t": "set", "p": "payload", "pt": "msg", "to": "リセットしました", "tot": "str"}
],
"x": 320,
"y": 180,
"wires": [["ex1b_debug"]]
},
{
"id": "ex1b_debug",
"type": "debug",
"z": "tab_flow_ex1b",
"name": "表示",
"active": true,
"tosidebar": true,
"console": false,
"tostatus": false,
"complete": "payload",
"targetType": "msg",
"x": 510,
"y": 140,
"wires": []
}
]
どちらを選ぶべき?
- パターンA(Function):複雑な条件分岐やループが必要な場合、JavaScriptに慣れている方向け
- パターンB(Change):シンプルな計算や代入だけで済む場合、GUI中心で完結させたい方向け
- 共通のポイント:どちらの方式で保存した flow変数も、お互いに読み書きできる(相互運用性あり)
例2: global変数で「設定値」を全フローから参照する
よくある場面: 温度の警告閾値、デバイス名、APIエンドポイントなど、複数のタブ(フロー)から同じ設定値を参照したいケース。global変数は全タブから参照できるので、このような「設定値の共有」に向いています。
フロー構成:
設定登録
→
global.threshold=30
→
登録確認
温度=35
→
判定
→
結果表示
ポイント:
- 最初に「設定登録」Injectを押して
global.threshold = 30 を保存
- 次に「温度=35」Injectを押すと、Changeノードが
global.threshold を取り出して比較
- JSONata式で、現在温度や閾値、超過判定を1つのJSONにまとめて出力
- 実運用では「設定登録」と「温度判定」は別タブに配置しても同じように動く
判定Changeノードの設定(2ルール):
ルール1: msg.threshold を global.threshold に設定(値の代入)
ルール2: msg.payload を JSONata に設定
式: {
"現在温度": payload,
"閾値": $globalContext("threshold"),
"警告": payload > $globalContext("threshold")
}
📋 サンプルフロー(クリックで展開)
[
{
"id": "tab_global_ex2",
"type": "tab",
"label": "global変数で設定共有",
"disabled": false,
"info": "",
"env": []
},
{
"id": "ex2_inject_set",
"type": "inject",
"z": "tab_global_ex2",
"name": "設定登録",
"props": [{"p": "payload"}],
"repeat": "",
"crontab": "",
"once": false,
"onceDelay": 0.1,
"topic": "",
"payload": "30",
"payloadType": "num",
"x": 120,
"y": 100,
"wires": [["ex2_change_set"]]
},
{
"id": "ex2_change_set",
"type": "change",
"z": "tab_global_ex2",
"name": "global.threshold=30",
"rules": [
{"t": "set", "p": "threshold", "pt": "global", "to": "30", "tot": "num"},
{"t": "set", "p": "payload", "pt": "msg", "to": "閾値を30に設定しました", "tot": "str"}
],
"x": 330,
"y": 100,
"wires": [["ex2_debug"]]
},
{
"id": "ex2_inject_temp",
"type": "inject",
"z": "tab_global_ex2",
"name": "温度=35",
"props": [{"p": "payload"}],
"repeat": "",
"crontab": "",
"once": false,
"onceDelay": 0.1,
"topic": "",
"payload": "35",
"payloadType": "num",
"x": 120,
"y": 180,
"wires": [["ex2_change_check"]]
},
{
"id": "ex2_change_check",
"type": "change",
"z": "tab_global_ex2",
"name": "閾値と比較",
"rules": [
{"t": "set", "p": "threshold", "pt": "msg", "to": "threshold", "tot": "global"},
{"t": "set", "p": "payload", "pt": "msg", "to": "{\"現在温度\": payload, \"閾値\": $globalContext(\"threshold\"), \"警告\": payload > $globalContext(\"threshold\")}", "tot": "jsonata"}
],
"x": 330,
"y": 180,
"wires": [["ex2_debug"]]
},
{
"id": "ex2_debug",
"type": "debug",
"z": "tab_global_ex2",
"name": "結果",
"active": true,
"tosidebar": true,
"console": false,
"tostatus": false,
"complete": "payload",
"targetType": "msg",
"x": 530,
"y": 140,
"wires": []
}
]
例3: context変数で「前回値」を覚えて差分を計算する
よくある場面: センサーの温度変化量を計算する、前回のAPIレスポンスと比較する、電力量計の増分を求めるなど。そのノード専用の記憶域としてcontext変数が役立ちます。
フロー構成:
温度=25
→
差分計算
→
結果
ポイント:
- Injectノードには異なる温度値を持つボタンを複数用意(25℃/28℃/23℃)
- Functionノード内で
context.get('lastValue') で前回値を取り出す
- 現在値と前回値の差分を計算し、上昇/下降/変化なしを判定
context.set('lastValue', ...) で今回の値を次回のために保存
- context変数はこのFunctionノード専用なので、他のノードからは見えない
Functionノードのコード:
const previous = context.get('lastValue');
const current = msg.payload;
if (previous === undefined) {
msg.payload = { current: current, message: "初回測定です" };
} else {
const diff = current - previous;
msg.payload = {
current: current,
previous: previous,
difference: diff,
trend: diff > 0 ? "上昇" : diff < 0 ? "下降" : "変化なし"
};
}
context.set('lastValue', current);
return msg;
📋 サンプルフロー(クリックで展開)
[
{
"id": "tab_ctx_ex3",
"type": "tab",
"label": "context変数で差分計算",
"disabled": false,
"info": "",
"env": []
},
{
"id": "ex3_inject_25",
"type": "inject",
"z": "tab_ctx_ex3",
"name": "温度=25",
"props": [{"p": "payload"}],
"repeat": "",
"crontab": "",
"once": false,
"onceDelay": 0.1,
"topic": "",
"payload": "25",
"payloadType": "num",
"x": 120,
"y": 80,
"wires": [["ex3_func_diff"]]
},
{
"id": "ex3_inject_28",
"type": "inject",
"z": "tab_ctx_ex3",
"name": "温度=28",
"props": [{"p": "payload"}],
"repeat": "",
"crontab": "",
"once": false,
"onceDelay": 0.1,
"topic": "",
"payload": "28",
"payloadType": "num",
"x": 120,
"y": 140,
"wires": [["ex3_func_diff"]]
},
{
"id": "ex3_inject_23",
"type": "inject",
"z": "tab_ctx_ex3",
"name": "温度=23",
"props": [{"p": "payload"}],
"repeat": "",
"crontab": "",
"once": false,
"onceDelay": 0.1,
"topic": "",
"payload": "23",
"payloadType": "num",
"x": 120,
"y": 200,
"wires": [["ex3_func_diff"]]
},
{
"id": "ex3_func_diff",
"type": "function",
"z": "tab_ctx_ex3",
"name": "差分計算",
"func": "const previous = context.get('lastValue');\nconst current = msg.payload;\n\nif (previous === undefined) {\n msg.payload = { current: current, message: \"初回測定です\" };\n} else {\n const diff = current - previous;\n msg.payload = {\n current: current,\n previous: previous,\n difference: diff,\n trend: diff > 0 ? \"上昇\" : diff < 0 ? \"下降\" : \"変化なし\"\n };\n}\n\ncontext.set('lastValue', current);\nreturn msg;",
"outputs": 1,
"timeout": 0,
"noerr": 0,
"initialize": "",
"finalize": "",
"libs": [],
"x": 320,
"y": 140,
"wires": [["ex3_debug"]]
},
{
"id": "ex3_debug",
"type": "debug",
"z": "tab_ctx_ex3",
"name": "結果",
"active": true,
"tosidebar": true,
"console": false,
"tostatus": false,
"complete": "payload",
"targetType": "msg",
"x": 510,
"y": 140,
"wires": []
}
]
実際に手を動かして、flow / context / global 変数の使い方を身につけましょう。各問題には難易度、要求仕様、ヒント、解答例フローが用意されています。
演習1: flow変数で訪問カウンターを作る初級
📝 課題:
Injectノードを押すたびに、flow変数 visitCount を +1 して、「◯回目の訪問です」というメッセージを Debug に表示してください。
💼 使いどころ: 複数のノードにまたがって回数を数え、次の処理でもその値を使う場面で使います。
🎯 要求仕様:
- Inject、Change、Debug の3ノードを使用(Functionノードは使わない)
- flow変数名:
visitCount
- ChangeノードのJSONata機能を使って、flow変数を +1 する
- msg.payload を「1回目の訪問です」のような文字列にする
✅ 成功の条件:
- 1回目のInject:Debug に「1回目の訪問です」と表示される
- 2回目のInject:「2回目の訪問です」と表示される
- 何度押しても順番にカウントアップしていく
- Node-REDを再起動すると 1 から再スタートする
💡 ヒント
Changeノードの設定(2ルール):
- ルール1: 値の代入(Set)
- 対象:
flow.visitCount
- 値のタイプ:
JSONata式
- 値:
($flowContext("visitCount") ? $flowContext("visitCount") : 0) + 1
- ルール2: 値の代入(Set)
- 対象:
msg.payload
- 値のタイプ:
JSONata式
- 値:
$flowContext("visitCount") & "回目の訪問です"
※ JSONataの & は文字列連結演算子です。
✅ 解答例フロー
[
{
"id": "tab_q1",
"type": "tab",
"label": "演習1 訪問カウンター",
"disabled": false,
"info": "",
"env": []
},
{
"id": "q1_inject",
"type": "inject",
"z": "tab_q1",
"name": "訪問",
"props": [{"p": "payload"}],
"repeat": "",
"crontab": "",
"once": false,
"onceDelay": 0.1,
"topic": "",
"payload": "",
"payloadType": "date",
"x": 120,
"y": 100,
"wires": [["q1_change"]]
},
{
"id": "q1_change",
"type": "change",
"z": "tab_q1",
"name": "カウント+1",
"rules": [
{"t": "set", "p": "visitCount", "pt": "flow", "to": "($flowContext(\"visitCount\") ? $flowContext(\"visitCount\") : 0) + 1", "tot": "jsonata"},
{"t": "set", "p": "payload", "pt": "msg", "to": "$flowContext(\"visitCount\") & \"回目の訪問です\"", "tot": "jsonata"}
],
"x": 310,
"y": 100,
"wires": [["q1_debug"]]
},
{
"id": "q1_debug",
"type": "debug",
"z": "tab_q1",
"name": "結果",
"active": true,
"tosidebar": true,
"console": false,
"tostatus": false,
"complete": "payload",
"targetType": "msg",
"x": 490,
"y": 100,
"wires": []
}
]
演習2: 独立した2つのフローの値を合算する初級
📝 課題:
センサーAとセンサーBの値を、それぞれ独立したフロー(別々のInjectチェーン)で受け取り、3つ目のフローで両方の最新値を使って合計と平均を計算してください。実運用では「センサーAとBはバラバラのタイミングで値が更新されるが、計算時には両方の最新値が必要」という場面がよくあります。
💼 使いどころ: 更新のタイミングが別々のセンサー値を、どちらの最新値もそろった状態で計算する場面で使います。
🎯 要求仕様:
- 3つの独立したフロー(すべて同じタブ内)を作成
- フロー1: Inject「センサーA=20」→ Change(flow.sensorA に保存)→ Debug
- フロー2: Inject「センサーB=60」→ Change(flow.sensorB に保存)→ Debug
- フロー3: Inject「計算実行」→ Change(flow.sensorA と flow.sensorB から合計と平均を計算)→ Debug
- センサーA と センサーB は別々のタイミングで押しても動作する(= flow変数で値が保持される)
- 計算実行時の出力は
{ "A": 20, "B": 60, "合計": 80, "平均": 40 } のJSON
- Functionノードは使わず、Changeノードだけで実装
✅ 成功の条件:
- センサーAを押す → Debug に「センサーA=20 を保存しました」と表示
- センサーBを押す → Debug に「センサーB=60 を保存しました」と表示
- 計算実行を押す → Debug に
{A: 20, B: 60, 合計: 80, 平均: 40} が表示
- センサーAの値を別の数値に変えて先に更新 → 計算実行すると最新値で計算される
- ABの取得順番(A→B でも B→A でも、片方だけ更新してから計算してもOK)に依存しない
なぜ flow変数なのか?
msg.payload だけで受け渡そうとすると、AとBが「同じ1本のフロー」に並んでいないと値が揃いません。ところがAとBは別々のタイミング、別々の入力経路から来るので、それぞれの値を「どこかに置いておく」必要があります。ここで flow変数が中継地点の役割を果たします。
💡 ヒント
センサーA保存のChangeノード(2ルール):
- ルール1: flow.sensorA を msg.payload に設定(型: msg)
- ルール2: msg.payload を JSONata
"センサーA=" & $flowContext("sensorA") & " を保存しました"
センサーB保存のChangeノード:同上で sensorA → sensorB に読み替え
計算のChangeノード(1ルール):
- ルール: msg.payload を JSONata式 に設定
- 式:
{
"A": $flowContext("sensorA"),
"B": $flowContext("sensorB"),
"合計": $flowContext("sensorA") + $flowContext("sensorB"),
"平均": ($flowContext("sensorA") + $flowContext("sensorB")) / 2
}
Injectノードの設定:
- センサーA: payload = 20(数値型)
- センサーB: payload = 60(数値型)
- 計算実行: payload = 空(タイムスタンプでOK)
✅ 解答例フロー
[
{
"id": "tab_q2b",
"type": "tab",
"label": "演習2 独立フローで値を合算",
"disabled": false,
"info": "",
"env": []
},
{
"id": "q2b_inject_a",
"type": "inject",
"z": "tab_q2b",
"name": "センサーA=20",
"props": [{"p": "payload"}],
"repeat": "",
"crontab": "",
"once": false,
"onceDelay": 0.1,
"topic": "",
"payload": "20",
"payloadType": "num",
"x": 130,
"y": 80,
"wires": [["q2b_change_a"]]
},
{
"id": "q2b_change_a",
"type": "change",
"z": "tab_q2b",
"name": "flow.sensorAに保存",
"rules": [
{"t": "set", "p": "sensorA", "pt": "flow", "to": "payload", "tot": "msg"},
{"t": "set", "p": "payload", "pt": "msg", "to": "\"センサーA=\" & $flowContext(\"sensorA\") & \" を保存しました\"", "tot": "jsonata"}
],
"x": 340,
"y": 80,
"wires": [["q2b_debug"]]
},
{
"id": "q2b_inject_b",
"type": "inject",
"z": "tab_q2b",
"name": "センサーB=60",
"props": [{"p": "payload"}],
"repeat": "",
"crontab": "",
"once": false,
"onceDelay": 0.1,
"topic": "",
"payload": "60",
"payloadType": "num",
"x": 130,
"y": 160,
"wires": [["q2b_change_b"]]
},
{
"id": "q2b_change_b",
"type": "change",
"z": "tab_q2b",
"name": "flow.sensorBに保存",
"rules": [
{"t": "set", "p": "sensorB", "pt": "flow", "to": "payload", "tot": "msg"},
{"t": "set", "p": "payload", "pt": "msg", "to": "\"センサーB=\" & $flowContext(\"sensorB\") & \" を保存しました\"", "tot": "jsonata"}
],
"x": 340,
"y": 160,
"wires": [["q2b_debug"]]
},
{
"id": "q2b_inject_calc",
"type": "inject",
"z": "tab_q2b",
"name": "計算実行",
"props": [{"p": "payload"}],
"repeat": "",
"crontab": "",
"once": false,
"onceDelay": 0.1,
"topic": "",
"payload": "",
"payloadType": "date",
"x": 120,
"y": 240,
"wires": [["q2b_change_calc"]]
},
{
"id": "q2b_change_calc",
"type": "change",
"z": "tab_q2b",
"name": "合計・平均を計算",
"rules": [
{"t": "set", "p": "payload", "pt": "msg", "to": "{\"A\": $flowContext(\"sensorA\"), \"B\": $flowContext(\"sensorB\"), \"合計\": $flowContext(\"sensorA\") + $flowContext(\"sensorB\"), \"平均\": ($flowContext(\"sensorA\") + $flowContext(\"sensorB\")) / 2}", "tot": "jsonata"}
],
"x": 340,
"y": 240,
"wires": [["q2b_debug"]]
},
{
"id": "q2b_debug",
"type": "debug",
"z": "tab_q2b",
"name": "結果",
"active": true,
"tosidebar": true,
"console": false,
"tostatus": false,
"complete": "payload",
"targetType": "msg",
"x": 550,
"y": 160,
"wires": []
}
]
演習3: global変数でユーザー設定を保存して参照する中級
📝 課題:
Injectで送った「ユーザー名」をglobal変数に保存し、別のInjectで挨拶メッセージを作るフローを作成してください。global変数を使うことで、設定値がフロー全体で共有されることを体験します。
💼 使いどころ: タブをまたいで共通の設定値を持ち回り、どのフローからも同じ値を参照する場面で使います。
🎯 要求仕様:
- Injectノード2つ、Changeノード2つ、Debugノード1つ(または複数)を使用
- 1つ目のフロー:Inject「名前を設定」→ Change → Debug
- msg.payload に入った文字列「Alice」を
global.userName に保存
- 2つ目のフロー:Inject「挨拶」→ Change → Debug
global.userName を取り出して、「こんにちは、Alice さん!」を msg.payload に設定
✅ 成功の条件:
- 「名前を設定」Injectを押す → Debug に「名前 Alice を保存しました」と表示
- 「挨拶」Injectを押す → Debug に「こんにちは、Alice さん!」と表示
- 別のタブ(フロー)に「挨拶」フローを移しても同じように動作する(= global変数の恩恵)
💡 ヒント
1つ目のChangeノード(名前保存):
- ルール1: global.userName を msg.payload に設定(型: msg)
- ルール2: msg.payload を JSONata
"名前 " & $globalContext("userName") & " を保存しました"
2つ目のChangeノード(挨拶生成):
- ルール: msg.payload を JSONata
"こんにちは、" & $globalContext("userName") & " さん!"
Injectノードの設定:
- 1つ目: payload = "Alice"(文字列型)
- 2つ目: payload は空(タイムスタンプでOK)
✅ 解答例フロー
[
{
"id": "tab_q3",
"type": "tab",
"label": "演習3 global変数で設定共有",
"disabled": false,
"info": "",
"env": []
},
{
"id": "q3_inject_set",
"type": "inject",
"z": "tab_q3",
"name": "名前を設定",
"props": [{"p": "payload"}],
"repeat": "",
"crontab": "",
"once": false,
"onceDelay": 0.1,
"topic": "",
"payload": "Alice",
"payloadType": "str",
"x": 130,
"y": 100,
"wires": [["q3_change_set"]]
},
{
"id": "q3_change_set",
"type": "change",
"z": "tab_q3",
"name": "global.userNameに保存",
"rules": [
{"t": "set", "p": "userName", "pt": "global", "to": "payload", "tot": "msg"},
{"t": "set", "p": "payload", "pt": "msg", "to": "\"名前 \" & $globalContext(\"userName\") & \" を保存しました\"", "tot": "jsonata"}
],
"x": 340,
"y": 100,
"wires": [["q3_debug"]]
},
{
"id": "q3_inject_greet",
"type": "inject",
"z": "tab_q3",
"name": "挨拶",
"props": [{"p": "payload"}],
"repeat": "",
"crontab": "",
"once": false,
"onceDelay": 0.1,
"topic": "",
"payload": "",
"payloadType": "date",
"x": 120,
"y": 180,
"wires": [["q3_change_greet"]]
},
{
"id": "q3_change_greet",
"type": "change",
"z": "tab_q3",
"name": "挨拶メッセージ生成",
"rules": [
{"t": "set", "p": "payload", "pt": "msg", "to": "\"こんにちは、\" & $globalContext(\"userName\") & \" さん!\"", "tot": "jsonata"}
],
"x": 330,
"y": 180,
"wires": [["q3_debug"]]
},
{
"id": "q3_debug",
"type": "debug",
"z": "tab_q3",
"name": "結果",
"active": true,
"tosidebar": true,
"console": false,
"tostatus": false,
"complete": "payload",
"targetType": "msg",
"x": 530,
"y": 140,
"wires": []
}
]
演習4: context変数で直近3回の移動平均を計算する上級
📝 課題:
Functionノード内でcontext変数を使って、直近3回の値の平均(移動平均)を計算するフローを作成してください。ノイズの多いセンサー値をなめらかにする実用的な処理です。
💼 使いどころ: ノイズの多いセンサー値を、過去の数回分を覚えておいてなめらかにする場面で使います。
🎯 要求仕様:
- Inject(数値送信)→ Function(移動平均) → Debug の構成
- Functionノード内で
context.get('history') / context.set('history', ...) を使用
- 直近3回までの値を配列で保持する(3回を超えたら古いものを削除)
- 出力は
{ current: 現在値, history: 履歴配列, average: 平均値 } のJSON
- Injectは3つ以上用意(例:10, 20, 30, 40, 50)
✅ 成功の条件:
- 1回目のInject(10):history=[10]、average=10
- 2回目のInject(20):history=[10, 20]、average=15
- 3回目のInject(30):history=[10, 20, 30]、average=20
- 4回目のInject(40):history=[20, 30, 40](10が押し出される)、average=30
- 5回目のInject(50):history=[30, 40, 50]、average=40
💡 ヒント
Functionノードの実装手順:
context.get('history') || [] で履歴配列を取得(無ければ空配列)
history.push(msg.payload) で現在値を追加
if (history.length > 3) history.shift() で4件目以降は先頭を削除
history.reduce((a, b) => a + b, 0) / history.length で平均を計算
context.set('history', history) で次回用に保存
- msg.payload に結果JSONをセットして return
注意: context.get で取得した配列を直接 push で変更しても、context.set で明示的に保存し直すのが安全です。
✅ 解答例フロー
[
{
"id": "tab_q4",
"type": "tab",
"label": "演習4 context移動平均",
"disabled": false,
"info": "",
"env": []
},
{
"id": "q4_inject_10",
"type": "inject",
"z": "tab_q4",
"name": "値=10",
"props": [{"p": "payload"}],
"repeat": "",
"crontab": "",
"once": false,
"onceDelay": 0.1,
"topic": "",
"payload": "10",
"payloadType": "num",
"x": 120,
"y": 60,
"wires": [["q4_func"]]
},
{
"id": "q4_inject_20",
"type": "inject",
"z": "tab_q4",
"name": "値=20",
"props": [{"p": "payload"}],
"repeat": "",
"crontab": "",
"once": false,
"onceDelay": 0.1,
"topic": "",
"payload": "20",
"payloadType": "num",
"x": 120,
"y": 110,
"wires": [["q4_func"]]
},
{
"id": "q4_inject_30",
"type": "inject",
"z": "tab_q4",
"name": "値=30",
"props": [{"p": "payload"}],
"repeat": "",
"crontab": "",
"once": false,
"onceDelay": 0.1,
"topic": "",
"payload": "30",
"payloadType": "num",
"x": 120,
"y": 160,
"wires": [["q4_func"]]
},
{
"id": "q4_inject_40",
"type": "inject",
"z": "tab_q4",
"name": "値=40",
"props": [{"p": "payload"}],
"repeat": "",
"crontab": "",
"once": false,
"onceDelay": 0.1,
"topic": "",
"payload": "40",
"payloadType": "num",
"x": 120,
"y": 210,
"wires": [["q4_func"]]
},
{
"id": "q4_inject_50",
"type": "inject",
"z": "tab_q4",
"name": "値=50",
"props": [{"p": "payload"}],
"repeat": "",
"crontab": "",
"once": false,
"onceDelay": 0.1,
"topic": "",
"payload": "50",
"payloadType": "num",
"x": 120,
"y": 260,
"wires": [["q4_func"]]
},
{
"id": "q4_func",
"type": "function",
"z": "tab_q4",
"name": "移動平均(直近3件)",
"func": "// このノード専用の context から、これまでの履歴を読み出す(初回は空の配列)\nconst history = context.get('history') || [];\n// 今回の値を末尾に足し、3件を超えたら一番古い値(先頭)を捨てる\nhistory.push(msg.payload);\nif (history.length > 3) history.shift();\n// 履歴の合計を件数で割って平均を出す\nconst average = history.reduce((a, b) => a + b, 0) / history.length;\n// 次回のために履歴を保存し直す\ncontext.set('history', history);\nmsg.payload = {\n current: msg.payload,\n history: history,\n average: average\n};\nreturn msg;",
"outputs": 1,
"timeout": 0,
"noerr": 0,
"initialize": "",
"finalize": "",
"libs": [],
"x": 330,
"y": 160,
"wires": [["q4_debug"]]
},
{
"id": "q4_debug",
"type": "debug",
"z": "tab_q4",
"name": "結果",
"active": true,
"tosidebar": true,
"console": false,
"tostatus": false,
"complete": "payload",
"targetType": "msg",
"x": 530,
"y": 160,
"wires": []
}
]
Part 1(msg編)と合わせると、Node-REDの変数の全体像が見えてきます。実際のプロジェクトでこれらを組み合わせて、より複雑なアプリケーションに挑戦してみてください。