我想要一个Node.js模块,它是一个包含多个文件的目录。我希望一个文件中的某些变量可以从其他文件访问,但不能从该模块外部的文件访问。可能吗?如何在Node中的2个文件之间共享模块专用数据?
因此,让我们假设下面的文件结构
` 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.js
和extra.js
中创建一个多文件service.js
和require
。这是对的吗?还有其他解决方案吗?
请添加一些代码作为例子来说明您的问题。 –
你到底需要什么?这个要求听起来很奇怪 - 是不是来自一个文件的模块外部的其他文件? – Bergi
@MthetheGGraves增加了一些代码和解释 – mrvn