Node.js and exported variables

后端 未结 2 1215
慢半拍i
慢半拍i 2021-01-17 01:36

I\'m trying to use one script for the communal storage of \"global\" variables, and other scripts can require that script to see those variables, but that appears to not be

2条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-17 01:59

    One way to accomplish what you are trying to do is to use a singleton type object as your "global" memory space and let's say this file is named NodeGlobalVars.js.

    exports.NodeGlobalVars = NodeGlobalVars;
    
    function NodeGlobalVars()
    {   
        //only do this if this is the first time the object has been used
        if(typeof(NodeGlobalVars.SingleInstance) === "undefined")
        {
            this.GlobalVariable1 = 1;
            this.GlobalVariable2 = 2;
    
            //set to this so we won't create more objects later
            NodeGlobalVars.SingleInstance = this;
        }
    
        return NodeGlobalVars.SingleInstance;   //return the single instance variable
    };
    

    Now in other files you want to get that data from and modify it, you can do the following in as many different files as you want:

    var NodeGlobalVars= require('../NodeGlobalVars/NodeGlobalVars.js').NodeGlobalVars;
    
    //now get access to the NodeGlobalVars
    var Globals = new NodeGlobalVars();
    
    //now log the state of GlobalVariable1 and modify the value of GlobalVariable2
    console.log("Global1: " + Globals.GlobalVariable1);
    Globals.GlobalVariable2++;
    

    You can modify the data freely from any other file and they will all point back to the same memory. In effect, you have created global memory space for a node application and have done so using a nice convenient like namespace Globals on the front of it to make it apparent that it is global.

    Now, whether you should do this or not, that's another question.

提交回复
热议问题