How can I share module-private data between 2 file

2020-05-06 03:09发布

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?

3条回答
Melony?
2楼-- · 2020-05-06 03:49

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;
};
查看更多
该账号已被封号
3楼-- · 2020-05-06 03:54

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
};
查看更多
我想做一个坏孩纸
4楼-- · 2020-05-06 03:56

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;
查看更多
登录 后发表回答