Skip to content Skip to sidebar Skip to footer

Global Variables Alternative

I want to create an array that is accessible to all the .js files. This array must also be updateable, and the updated changes must be reflected in all the other files using that

Solution 1:

Proper modularity in node.js does not use actual globals as that makes actually taking advantage of reusable modules more complicated and makes for possible conflicts with other globals.

One design pattern that can be used instead is to put the shared data in its own module and then just require() in that module wherever needed.

// shared-data.jsvarmySharedArray= [...];

module.exports = {
    mySharedArray: mySharedArray
}

Then, in each module that wants to have access to that array, you can do this:

// someothermodule.jsvar sharedArray = require('./shared-data.js').mySharedArray;


// this modification will change the main array and will be seen by// all modules that are sharing it
sharedArray.push("moreData");

This works because when arrays are assigned in Javascript, they are not copied, but instead a pointer to the original array is shared. So, any modifications to the assigned value is just pointing at the original object and thus changes the original array. Thus, all modules would have access to the same original array.


I just tested this concept in my own three files and it works fine. Here are my three files:

Server File:

// shared-server.jsvar express = require('express');
var app = express();
var server = app.listen(80);
var shared = require('./shared-var');
require('./shared-interval.js')

var cntr = 0;

app.use(express.static('public'));

app.get("/test", function(req, res) {
    shared.mySharedArray.push(++cntr);
    shared.get();
    res.send(200,'message received');
});

Shared Variable File:

//shared-var.jsvar mySharedArray = ['helo']; 
module.exports = {
    mySharedArray: mySharedArray,
    get: function(){
        console.log(mySharedArray);
    } 
}

Interval File:

//shared-interval.jsvar interval = setInterval(function() {
    require('./shared-var').get();
}, 1000);

When I run this, it outputs the value of mySharedArray every second. Each time I go to http://localhost/test with my browser, it adds a new value to mySharedArray and I see that in the console. This is the behavior I would expect.

Solution 2:

You could put them in a separate module that gets required in whatever module you need it in, else you could use a seperate storage service such as redis or memcached to store your array of data.

Post a Comment for "Global Variables Alternative"