2013-06-27 96 views
0

我想要一个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.jsextra.js中创建一个多文件service.jsrequire。这是对的吗?还有其他解决方案吗?

+1

请添加一些代码作为例子来说明您的问题。 –

+0

你到底需要什么?这个要求听起来很奇怪 - 是不是来自一个文件的模块外部的其他文件? – Bergi

+0

@MthetheGGraves增加了一些代码和解释 – mrvn

回答

0

我想从一个文件中的一些增值经销商是从其他文件访问,而不是从文件模块外部

是的,这是可能的。您可以在其他文件加载到你的模块,并把它交给一个特权功能,提供从你的模块范围访问特定的变量,或者只是把它交给值本身:

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

好,Y OU可以能够与“全局”命名空间来做到这一点:

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

然后

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

听起来很有希望。我会在今天晚些时候尝试,谢谢 – mrvn

+0

“*但不是来自模块外部的文件*” – Bergi

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; 
}; 
相关问题