# Function node -local variables-

**URL:** <https://discourse.nodered.org/t/function-node-local-variables/95461>\
**Category:** General\
**Created:** [17 February 2025 11:22 UTC](https://discourse.nodered.org/t/function-node-local-variables/95461 "2025-02-17T11:22:22Z")\
**Posts on this page:** 11\
**Page:** 1

<div class="post-metadata">

**Author:** ![pin32](https://avatars.discourse-cdn.com/v4/letter/p/2bfe46/32.png) [@pin32](https://discourse.nodered.org/u/pin32)\
**Post date:** [17 February 2025 11:22 UTC](https://discourse.nodered.org/t/function-node-local-variables/95461/1 "2025-02-17T11:22:22Z")

</div>

Can you use local or time variables within the code?  
It seems that they are reset at each cycle and not at startup vome I would expect.  
in the case how to get the loss of persistence at startup but not in the cycle?

---

<div class="post-metadata">

**Author:** ![jbudd](https://avatars.discourse-cdn.com/v4/letter/j/5f8ce5/32.png) [@jbudd](https://discourse.nodered.org/u/jbudd)\
**Post date:** [17 February 2025 11:50 UTC](https://discourse.nodered.org/t/function-node-local-variables/95461/2 "2025-02-17T11:50:34Z")

</div>

It is fundamental to Node-red that generally, each node works with the message sent to it without any knowledge of previous messages.

So in a function node a variable is initialised afresh for each message. Once the message is processed the variable is destroyed.

There is of course provision for variables outside of the flow of messages - context variables.  
Their scope can be confined to a single node, an editor tab (flow) or global.

```auto
let subtotal = context.get('subtotal') ?? 0 // or flow.get, global.get
subtotal += msg.payload
context.set('subtotal', subtotal)

```

---

<div class="post-metadata">

**Author:** ![Colin](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/colin/32/17040_2.png) [@Colin](https://discourse.nodered.org/u/Colin)\
**Post date:** [17 February 2025 13:35 UTC](https://discourse.nodered.org/t/function-node-local-variables/95461/3 "2025-02-17T13:35:50Z")

</div>

If @jbudd's suggestion does not solve your problem then please give an example of exactly what you mean.

---

<div class="post-metadata">

**Author:** ![pin32](https://avatars.discourse-cdn.com/v4/letter/p/2bfe46/32.png) [@pin32](https://discourse.nodered.org/u/pin32)\
**Post date:** [17 February 2025 14:57 UTC](https://discourse.nodered.org/t/function-node-local-variables/95461/4 "2025-02-17T14:57:00Z")

</div>

```auto
// Definisci la variabile 'chiave' all'inizio del codice, così puoi modificarla facilmente
let chiave = "GPIOIN_7"; // Sostituisci questa stringa con la chiave che desideri utilizzare

// Recupera il valore precedente dal flusso
let valoreMemorizzato = flow.get('valoreMemorizzato') || ''; // Usa una stringa vuota come valore di default

// Inizializza lo stato
let stato = "Online"; // Lo stato predefinito è "Online"

// Verifica se il messaggio in ingresso è "agg"
if (msg.payload === "agg") {
    // Se la richiesta è "agg", invia l'ultimo valore memorizzato su out1
    msg.payload = valoreMemorizzato; // Invia il valore precedente memorizzato
    let obj = createObject(); // Crea l'oggetto da inviare su out2
    node.send([msg, { payload: obj }, { payload: stato }]); // Invia il messaggio su out1, l'oggetto su out2, e lo stato su out3
    return null; // Non inviare nuovamente il messaggio
}

// Normalizzazione dell'ingresso (gestisce 1/0, ON/OFF)
if (msg.payload === 1 || msg.payload === "ON" || msg.payload === "on") {
    msg.payload = "ON";
} else if (msg.payload === 0 || msg.payload === "OFF" || msg.payload === "off") {
    msg.payload = "OFF";
} else {
    msg.payload = "Invalid input"; // Gestione di casi imprevisti
    stato = "Offline"; // In caso di input non valido, imposta lo stato su "Offline"
}

// Confronto con il valore precedente
if (msg.payload !== valoreMemorizzato) {
    // Se il valore è diverso, invia il messaggio su out1 e l'oggetto su out2
    flow.set('valoreMemorizzato', msg.payload); // Memorizza nel contesto di flusso
    let obj = createObject(); // Crea l'oggetto da inviare su out2
    node.send([msg, { payload: obj }, { payload: stato }]); // Invia il messaggio su out1, l'oggetto su out2, e lo stato su out3
    return null; // Non inviare il messaggio direttamente
} else {
    // Se il valore è lo stesso, non inviare nulla (evitare operazioni non necessarie)
    return null; // Ignora il messaggio
}

// Funzione per creare l'oggetto da inviare su out2
function createObject() {
    return {
        "name": chiave, // Usa la variabile chiave
        "stat_t": `DATI FOTOVOLTAICO/INGRESSI/${chiave}`, // Usa la variabile chiave
        "avty_t": `DATI FOTOVOLTAICO/INGRESSI/${chiave}/LWT`, // Usa la variabile chiave
        "cmd_t": `DATI FOTOVOLTAICO/INGRESSI/${chiave}/command`, // Usa la variabile chiave
        "pl_avail": "Online",
        "pl_not_avail": "Offline",
        "uniq_id": chiave, // Usa la variabile chiave
        "icon": "mdi:electric-switch",
        "dev": {
            "ids": ["Quadro Domotica"],
            "name": "Quadro Domotica",
            "mf": "TopPino",
            "mdl": "Aggregatore mqtt",
            "sw": "0.1",
            "sa": "Fotovoltaico",
        },
    };
}

```

---

<div class="post-metadata">

**Author:** ![pin32](https://avatars.discourse-cdn.com/v4/letter/p/2bfe46/32.png) [@pin32](https://discourse.nodered.org/u/pin32)\
**Post date:** [17 February 2025 15:00 UTC](https://discourse.nodered.org/t/function-node-local-variables/95461/5 "2025-02-17T15:00:41Z")

</div>

in this code I need to forget the ultimate value but can’t figure out how to do

```auto
valoreMemorizzato 

```

I have to reset it

---

<div class="post-metadata">

**Author:** ![jbudd](https://avatars.discourse-cdn.com/v4/letter/j/5f8ce5/32.png) [@jbudd](https://discourse.nodered.org/u/jbudd)\
**Post date:** [17 February 2025 15:31 UTC](https://discourse.nodered.org/t/function-node-local-variables/95461/6 "2025-02-17T15:31:35Z")

</div>

Not sure I understand the question but you can delete a context variable with a change node.

In a function saving a value of undefined will delete it.

---

<div class="post-metadata">

**Author:** ![pin32](https://avatars.discourse-cdn.com/v4/letter/p/2bfe46/32.png) [@pin32](https://discourse.nodered.org/u/pin32)\
**Post date:** [17 February 2025 16:00 UTC](https://discourse.nodered.org/t/function-node-local-variables/95461/7 "2025-02-17T16:00:01Z")

</div>

I’m crazy about this thing, you can give me a specific example on the code posted, what I want to get is that at the first start does not have to perform a comparison but send directly the value on the outputs (3). to get this I’m trying to make forget the value saved in context, another alternative is just skip the comparison, but only at a restart of the node, during normal flow must make comparisons to avoid repeated sends.

---

<div class="post-metadata">

**Author:** ![jbudd](https://avatars.discourse-cdn.com/v4/letter/j/5f8ce5/32.png) [@jbudd](https://discourse.nodered.org/u/jbudd)\
**Post date:** [17 February 2025 16:04 UTC](https://discourse.nodered.org/t/function-node-local-variables/95461/8 "2025-02-17T16:04:28Z")

</div>

Apologies Giuseppe but it's clear English is not your first language and I have no Italian.

I can not tell what you are trying to do.

Can you perhaps explain again using very short sentences?  
A diagram might help too.

If necessary we can use the internet to translate.

---

<div class="post-metadata">

**Author:** ![pin32](https://avatars.discourse-cdn.com/v4/letter/p/2bfe46/32.png) [@pin32](https://discourse.nodered.org/u/pin32)\
**Post date:** [17 February 2025 16:08 UTC](https://discourse.nodered.org/t/function-node-local-variables/95461/9 "2025-02-17T16:08:52Z")

</div>

I’m using a translator... I’m Italian.  
I will try to make a diagram

---

<div class="post-metadata">

**Author:** ![Colin](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/colin/32/17040_2.png) [@Colin](https://discourse.nodered.org/u/Colin)\
**Post date:** [17 February 2025 17:19 UTC](https://discourse.nodered.org/t/function-node-local-variables/95461/10 "2025-02-17T17:19:12Z")

</div>

If you want to know if this is the first time through a function node since a node-red restart you can do

```auto
let firstTime = context.get("firstTime") ?? true
if (firstTime) {
  context.set("firstTime", false)
  // do things you want to do the first time
} else {
  // do things when it is not the first time
}

```

[Edit] That is unless, in settings.js, you have set the default context storage to 'file', in which case you would have to specify the `memory` context in the get and set functions.

---

<div class="post-metadata">

**Author:** ![system](https://us1.discourse-cdn.com/flex026/uploads/nodered/original/1X/d073cd938eafa2e558d7c2cd59003b3ef4963033.png) [@system](https://discourse.nodered.org/u/system)\
**Post date:** [18 May 2025 17:19 UTC](https://discourse.nodered.org/t/function-node-local-variables/95461/11 "2025-05-18T17:19:26Z")

</div>

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.
