在node.js中,模块中的一个文件如何看到模块中另一个文件中的函数?

时间:2012-07-02 07:45:50

标签: javascript node.js module

在包含./modx中的两个文件的模块中:modx.jshelper.js

./镆铘/的package.json:

{ "name" : "module x",
  "main" : "./modx.js" }

./镆铘/ helper.js:

function subFunc() { }

./镆铘/ modx.js:

exports.mainFunc = function() {
   var x = subFunc();
}

subFunc()模块中的helper.js modx.js时,如何modx {{1}}对{{1}}可见?

2 个答案:

答案 0 :(得分:3)

内部./modx/helper.js

var subFunc = function subFunc() {}
exports.subFunc = subFunc;

内部.modx / modx.js

var helper = require('./helper.js');
exports.mainFunc() {
    var x = helper.subFunc();
}

这里的结果是helper.js中的subFunc函数是外部可用的,modx.js中的mainFunc是外部可用的。

答案 1 :(得分:2)

脚本A中可见的脚本B中唯一的对象是module.exports。将对象/函数添加到module.exports(就像您使用mainFunc一样)使它们从外部可见。没有其他办法。