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 to the module. Is it possible?

So let's suppose the following file structure

` module/
  | index.js
  | extra.js
  ` additional.js

In index.js:

var foo = 'some value';
...
// make additional and extra available for the external code
module.exports.additional = require('./additional.js');
module.exports.extra = require('./extra.js');

In extra.js:

// some magic here
var bar = foo; // where foo is foo from index.js

In additional.js:

// some magic here
var qux = foo; // here foo is foo from index.js as well

Additional and Extra are implementing some business logic (independent from each other) but need to share some module-internal service data which should not be exported.

The only solution that I see is to create one more file, service.js and require it from both additional.js and extra.js. Is it correct? Are there any other solutions?

Answers:

Answer

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 here
  var 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;
};
Answer

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

//index.js
global.foo = "some value";

and then

//extra.js
var bar = global.foo;
Answer

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:

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

extra.js:

module.exports = function(foo){
  // some magic here
  var 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 here
  var qux = foo; // foo is the foo from index.js again
  // instead of assigning the magic to exports, return it
};

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.