0

at the beginning of my code, I create a new instance of my global variable DT, but when I try to reassign it a new object in a method my global variable doesn't change.

const functions = require('firebase-functions');
const DecisionTree = require("decision-tree")
var firebase = require('firebase-admin');
const cors = require('cors')({origin: true});


......

var boards;
var dt;
var training_dat;

var class_name = "NextMove";
var features = ["C1", "C2", "C3", "C4", "C5", "C6", "C7", "C7", "C9"];

ref.once('value').then(function(snap) {
    boards = snap.val(); // query all data
    training_data = new Array();
    for(var B in boards){
        training_data.push(boards[B]);
    }
    dt = new DecisionTree(training_data, class_name, features);
    // HERE dt is a model with 500 rows.
});



exports.train = functions.https.onRequest((request, response) => {
.....

    dt=new DecisionTree(new_training_data, class_name, features);
//HERE dt is a model with 1000 rows
    response.send({output: "Training"});
});

exports.DOSOMETHING = functions.https.onRequest((request, response) => {
    // if i call dt here it is still a model with 500 rows.
    response.send({output: "Done"});
});

So I start my script, I get that dt is 500 rows. If I call "train" I get that it is 1000 rows. But when I call "DOSOMETHING" my variable dt has still 500 rows, like the precedent method didn't affect him.

I'm sorry it may sound stupid but I can't figure it out;

Hyyan Abo Fakher
  • 3,497
  • 3
  • 21
  • 35
JackFener
  • 21
  • 7

1 Answers1

1

Node.js does not put variables declared with var into global scope. (see related Question).

Whilst you can create a global by assigning a value to dt without using the var keyword, it errors in strict mode . You could try assigning a value to global.dt instead of dt to create and access a global value without strict mode errors.

Per Node.js documentation requiring a module multiple times always returns the same cached module.exports object that was created when the file was first required. Hence you should also be able to require an empty js file, say appdata.js, anywhere you want to access a common name space object within an applicataion.

traktor
  • 17,588
  • 4
  • 32
  • 53