【问题标题】:How can I share module-private data between 2 files in Node?如何在 Node 中的 2 个文件之间共享模块私有数据?
【发布时间】:2013-06-27 03:32:36
【问题描述】:

我想要一个用于 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 实现了一些业务逻辑(相互独立),但需要共享一些不应导出的模块内部服务数据。

我看到的唯一解决方案是从additional.jsextra.js 再创建一个文件service.jsrequire。这是正确的吗?还有其他解决方案吗?

【问题讨论】:

  • 请添加一些代码作为示例来说明您的问题。
  • 你到底需要这个做什么?这个要求听起来很奇怪 - 不是来自一个文件的模块外部的其他文件吗?
  • @MatthewGraves 添加了一些代码和解释

标签: javascript node.js


【解决方案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;
};

【讨论】:

    【解决方案2】:

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

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

    然后

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

    【讨论】:

    • "但不是来自模块外部的文件"
    【解决方案3】:

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

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

    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
    };
    

    【讨论】:

      猜你喜欢
      • 2017-01-21
      • 2019-03-30
      • 1970-01-01
      • 2014-12-23
      • 2019-12-21
      • 2017-09-06
      • 2015-10-08
      • 2017-10-04
      • 1970-01-01
      相关资源
      最近更新 更多