Node-RED 変数タイプガイド Part 2
context系変数(記憶するデータ)

☁️ クラウドOK 環境とは?

このページは Part 1(msg編) の続編です。msgオブジェクトがノード間を流れる「一時的なデータ」だったのに対して、ここで扱う context系変数 は、フローが終わっても値を保持し続ける「記憶するデータ」を扱います。

Node-REDの3種類の変数(マップ再掲)

Node-REDで使う変数は大きく3種類に分けられます。このページでは ②context系変数 を詳しく扱います。

① msgオブジェクト

流れるデータ

ノード間を1回だけ流れて、使い終わったら消える。payload、topicなどのプロパティを持つ。

Part 1 で解説 →
このページ

② context系変数

記憶するデータ

フローが終わっても値が残る。context / flow / global の3スコープで共有範囲を選べる。

Part 2 で解説中

③ JavaScript変数

Function内の計算用

Functionノード内でのみ使う let / const / var の変数。処理が終わると消える。

JSガイドへ →

1. なぜcontext系変数が必要か?

msgオブジェクトは「ノードからノードへ流れる荷物」のようなもので、1本のフローの中でしか値を共有できません。しかし実際にアプリを作ると、msgだけでは解決できない場面に出会います。

msgだけでは困る3つの典型例

場面A: 前回の値と比べたい

温度センサーが値を送ってきたとき、「前回より上昇したか下降したか」を判定したい。でも msg には今回の値しか入っていない。前回値をどこかに覚えておく必要がある。

場面B: 複数の入力経路を合わせたい

センサーAとセンサーBがバラバラのタイミングで別々のInjectから値を送ってくる。両方の最新値を使って合計や平均を計算したいが、msg.payload だけでは片方しか伝わらない。

場面C: 全タブで同じ設定を使いたい

APIキー、警告閾値、デバイス名などの設定値を複数のタブから参照したい。各フローに同じ値を書くとメンテナンスが大変。

context系変数の役割:

これら3つの場面で必要になるのが「フローを超えて値を覚えておく仕組み」です。それが context / flow / global の3つのスコープを持つ context系変数です。「どこまでの範囲で共有したいか」によって、使い分けます。

2. context / flow / global の3つのスコープ

context系変数は、宣言の仕方(APIの呼び分け)によってスコープ(共有範囲)が変わります。どの範囲まで値を共有したいかによって使い分けましょう。

context(ノード)

範囲:定義されたノード内のみ

有効期限:Node-REDを再起動するまで

宣言方法:context.set() / context.get()

context.set('lastValue', 25); const val = context.get('lastValue');
例:
特定のFunctionノード内でのみ使用する前回値や状態を保存

flow(フロー)

範囲:同じフロー(タブ)内のすべてのノード

有効期限:Node-REDを再起動するまで

宣言方法:flow.set() / flow.get()

flow.set('counter', 0); const count = flow.get('counter');
例:
同じフロー内の複数ノードで共有するカウンター値や設定値

global(グローバル)

範囲:すべてのフロー(全タブ)

有効期限:Node-REDを再起動するまで

宣言方法:global.set() / global.get()

global.set('apiKey', 'xxx'); const key = global.get('apiKey');
例:
全フローで共有するAPIキーやユーザー設定
使い分けの3原則:
共通の注意点:

3. context系変数の使い方

context系変数は、ChangeノードのGUI操作と Functionノード内のJavaScript のどちらでも読み書きできます。目的と好みに応じて使い分けましょう。

Changeノードで読み書きする(JavaScript不要)

Changeノードの「値の代入」ルールで、対象や値のタイプとして flow / global を選べます。JavaScriptを書かなくてもGUI操作だけでcontext系変数を操作できます。

やりたいこと Changeノードの設定
msg.payload の値を flow.x に保存 ルール: Set → flow.x を msg.payload に設定
global.y の値を msg.payload に読み込む ルール: Set → msg.payload を global.y に設定
flow.counter に固定値 0 を入れる ルール: Set → flow.counter を 数値 0 に設定
flow.counter を +1 する ルール: Set → flow.counter を JSONata式 ($flowContext("counter") ? $flowContext("counter") : 0) + 1
JSONata関数で context系変数を読む:

Functionノードで読み書きする(JavaScript)

Functionノード内では、context / flow / global の3つのオブジェクトが使えます。条件分岐や計算ロジックが複雑な場合は、こちらのほうが柔軟です。

操作 API 例
値を保存 xxx.set(キー, 値) flow.set('counter', 5)
値を取得 xxx.get(キー) const n = flow.get('counter')
未設定時のデフォルト xxx.get(キー) || 既定値 const n = flow.get('counter') || 0
値を削除 xxx.set(キー, undefined) flow.set('counter', undefined)
// Functionノード内のコード例 // 現在の flow.counter を取得し、+1 して保存 let count = flow.get('counter') || 0; count += 1; flow.set('counter', count); // 取得した値を msg.payload に入れて次のノードに渡す msg.payload = count; return msg;
どちらを使うか迷ったら:

4. 実用フロー例

ここでは、context系変数がよく使われる場面を、実際にNode-REDにインポートして動かせるフロー付きで紹介します。各例のサンプルフローをコピーしてエディターに読み込み、手を動かしながら動作を確認してみてください。

サンプルフローの使い方:
  1. 下のJSONの「コピー」ボタンでクリップボードにコピー
  2. Node-REDエディターのメニュー → 「読み込み」 → 「クリップボード」に貼り付け
  3. 「新しいフローとして」を選んで読み込み → デプロイして動作確認

例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 → 判定 → 結果表示

ポイント:

判定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 → 差分計算 → 結果

ポイント:

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": [] } ]
3つの例の使い分けまとめ:

5. よくある使い方のパターン

パターン1: ノード内での記憶 → context

そのノード内だけで使う一時データや状態。Functionノード内でのカウンターや前回値の保存など

パターン2: フロー内で共有 → flow

同じタブ内の複数ノードで使いたいデータ。カウンター、最後の値、設定値など

パターン3: 全体で共有 → global

すべてのフローで使いたいデータ。APIキー、ユーザー設定、共通の定数など

パターン4: 独立フロー間の中継 → flow

別々のタイミングや入力経路で来るセンサー値を、1本のフローで合算したい時の中継点

注意: global変数は便利ですが、使いすぎるとフローが複雑になります。本当に必要な場合だけ使用しましょう。まずは flow変数で足りないか検討してください。

6. 演習問題

実際に手を動かして、flow / context / global 変数の使い方を身につけましょう。各問題には難易度、要求仕様、ヒント、解答例フローが用意されています。

演習1: flow変数で訪問カウンターを作る初級

📝 課題:

Injectノードを押すたびに、flow変数 visitCount を +1 して、「◯回目の訪問です」というメッセージを Debug に表示してください。

💼 使いどころ: 複数のノードにまたがって回数を数え、次の処理でもその値を使う場面で使います。

🎯 要求仕様:

✅ 成功の条件:

💡 ヒント

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はバラバラのタイミングで値が更新されるが、計算時には両方の最新値が必要」という場面がよくあります。

💼 使いどころ: 更新のタイミングが別々のセンサー値を、どちらの最新値もそろった状態で計算する場面で使います。

🎯 要求仕様:

✅ 成功の条件:

なぜ 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変数を使うことで、設定値がフロー全体で共有されることを体験します。

💼 使いどころ: タブをまたいで共通の設定値を持ち回り、どのフローからも同じ値を参照する場面で使います。

🎯 要求仕様:

✅ 成功の条件:

💡 ヒント

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回の値の平均(移動平均)を計算するフローを作成してください。ノイズの多いセンサー値をなめらかにする実用的な処理です。

💼 使いどころ: ノイズの多いセンサー値を、過去の数回分を覚えておいてなめらかにする場面で使います。

🎯 要求仕様:

✅ 成功の条件:

💡 ヒント

Functionノードの実装手順:

  1. context.get('history') || [] で履歴配列を取得(無ければ空配列)
  2. history.push(msg.payload) で現在値を追加
  3. if (history.length > 3) history.shift() で4件目以降は先頭を削除
  4. history.reduce((a, b) => a + b, 0) / history.length で平均を計算
  5. context.set('history', history) で次回用に保存
  6. 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": [] } ]
演習のチェックポイント:

7. チートシート

変数の種類 スコープ(共有範囲) Changeノードでの指定 Functionノードでの指定 典型的な用途
context そのノード内のみ context.xxx context.get() / set() 前回値、ノード内カウンター
flow 同じタブ内のすべてのノード flow.xxx flow.get() / set() 共有カウンター、センサー値中継
global すべてのタブ(フロー) global.xxx global.get() / set() APIキー、全体設定

JSONata関数(Changeノード等で使用)

関数 用途 例
$flowContext("キー") flow変数の値を読み取る $flowContext("counter") + 1
$globalContext("キー") global変数の値を読み取る $globalContext("threshold")
& 文字列連結(JavaScriptの + に相当) "カウント: " & $flowContext("counter")

まとめ

Part 2 の要点:

Part 1(msg編)と合わせると、Node-REDの変数の全体像が見えてきます。実際のプロジェクトでこれらを組み合わせて、より複雑なアプリケーションに挑戦してみてください。


Node-RED Variable Types Guide Part 2: context系変数
💻 Happy Coding with Node-RED! 🚀

🏠