2013-06-27 94 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; 
}; 
相關問題