0

我想要一个用于 Node.js 的模块,它是一个包含多个文件的目录。我希望一个文件中的一些变量可以从其他文件访问,但不能从模块外部的文件访问。可能吗?

所以让我们假设以下文件结构

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

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');

extra.js

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

additional.js

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

Additional 和 Extra 正在实现一些业务逻辑(彼此独立),但需要共享一些不应导出的模块内部服务数据。

我看到的唯一解决方案是再创建一个文件,service.jsrequire来自additional.jsextra.js. 这是对的吗?还有其他解决方案吗?

4

3 回答 3

1

你能把想要的东西传进去吗?

//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;
};
于 2013-06-27T04:16:21.180 回答
0

好的,您可以使用“全局”命名空间来执行此操作:

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

接着

//extra.js
var bar = global.foo;
于 2013-06-27T04:03:20.020 回答
0

我希望一个文件中的一些变量可以从其他文件访问,但不能从模块外部的文件访问

对的,这是可能的。您可以将该其他文件加载到您的模块中,并将其交给一个特权函数,该函数提供从您的模块范围内访问特定变量的权限,或者只是将其交给值本身:

index.js:

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

额外的.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
};

附加.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
};
于 2013-06-27T03:46:05.280 回答