如何在Node中的两个文件之间共享模块私有数据

How can I share module-private data between 2 files in Node?

本文关键字:之间 文件 两个 共享 模块 数据 Node      更新时间:2023-09-26

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

因此,让我们假设以下文件结构

` 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。这是正确的吗?还有其他解决方案吗?

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

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

好的,您可以使用"全局"名称空间:

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

然后

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

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

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

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