导出模块Node.js
这个问题在这里已经有了答案:
只需要一个模块A(例如,在模块B中)不会使A的功能在其他模块中可访问。 通常情况下,他们甚至无法在模块B中访问。
要从另一个模块访问函数(或任何值),该其他模块必须导出它们。 以下方案不起作用:
// module-a.js
function firstFunction () {}
function secondFunction () {}
// module-b.js
var helper_handleSentences = require('/handleSentences.js');
// do something with 'helper_handleSentences'
module.exports = function (a) {
return helper_handleSentences(a);
}
正如你所看到的, module-a.js
不会导出任何内容。 因此,变量a
保存默认的导出值,它是一个空对象。
在你的情况下,你也可以
1.在mainModule.js
需要两个模块
// handleSentences.js
function doSomethingSecret () {
// this function can only be accessed in 'handleSentences.js'
}
function handleSentences () {
// this function can be accessed in any module that requires this module
doSomethingSecret();
}
module.exports = handleSentences;
// formatModule.js
var helper_handleSentences = require('/handleSentences.js');
// do something with 'helper_handleSentences'
module.exports = function (a) {
return helper_handleSentences(a);
};
// mainModule.js
var helper_handleSentences = require('/handleSentences.js');
var helper_formatModule = require('/formatModule.js');
// do something with 'helper_handleSentences' and 'helper_formatModule'
2.将两个模块的导出值合并到一个对象中
// handleSentences.js
function doSomethingSecret () {
// this function can only be accessed in 'handleSentences.js'
}
function handleSentences () {
// this function can be accessed in any module that requires this module
doSomethingSecret();
}
module.exports = handleSentences;
// formatModule.js
var helper_handleSentences = require('/handleSentences.js');
// do something with 'helper_handleSentences'
function formatModule (a) {
return helper_handleSentences(a);
};
module.exports = {
handleSentences: helper_handleSentences,
format: formatModule
};
// mainModule.js
var helper_formatModule = require('/formatModule.js');
// use both functions as methods
helper_formatModule.handleSentences();
helper_formatModule.format('...');
链接地址: http://www.djcxy.com/p/97015.html