Skip to content Skip to sidebar Skip to footer

How Can I Share Module-private Data Between 2 Files In Node?

I would like to have a module for Node.js that is a directory with several files. I'd like some vars from one file to be accessible from other file, but not from the files external

Solution 1:

Can you just pass the desired stuff in?

//index.js:var foo = 'some value';
module.exports.additional = require('./additional.js')(foo);
module.exports.extra = require('./extra.js')(foo);

//extra.js:module.exports = function(foo){
  var extra = {};
  // some magic herevar bar = foo; // where foo is foo from index.js
  extra.baz = function(req, res, next){};
  return extra;
};

//additional.js:module.exports = function(foo){
  var additonal = {};
  additional.deadbeef = function(req, res, next){
    var qux = foo; // here foo is foo from index.js as well
    res.send(200, qux);
  };
  return additional;
};

Solution 2:

Okay, you may be able to do this with the "global" namespace:

//index.jsglobal.foo = "some value";

and then

//extra.jsvar bar = global.foo;

Solution 3:

I'd like some vars from one file to be accessible from other file, but not from the files external to the module

Yes, it is possible. You can load that other file into your module and hand it over a privileged function that offers access to specific variables from your module scope, or just hand it over the values themselves:

index.js:

varfoo='some value';
module.exports.additional = require('./additional.js')(foo);
module.exports.extra = require('./extra.js')(foo);

extra.js:

module.exports = function(foo){
  // some magic herevar bar = foo; // foo is the foo from index.js// instead of assigning the magic to exports, return it
};

additional.js:

module.exports = function(foo){
  // some magic herevar qux = foo; // foo is the foo from index.js again// instead of assigning the magic to exports, return it
};

Post a Comment for "How Can I Share Module-private Data Between 2 Files In Node?"