简体   繁体   English

在node.js中,模块中的一个文件如何查看模块中另一个文件中的功能?

[英]in node.js, how does one file in a module see functions in another file in the module?

in a module containing two files in ./modx : modx.js and helper.js : 在一个模块中,该模块在./modx包含两个文件: modx.jshelper.js

./modx/package.json: ./modx/package.json:

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

./modx/helper.js: ./modx/helper.js:

function subFunc() { }

./modx/modx.js: ./modx/modx.js:

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

how do I make subFunc() in helper.js visible to modx.js when both are in the modx module? 我怎么做subFunc()helper.js可见modx.js当两者都是在modx模块?

Inside ./modx/helper.js 在./modx/helper.js内部

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

Inside .modx/modx.js 内部.modx / modx.js

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

The result here is that the subFunc function in helper.js is externally available and the mainFunc in modx.js is externally available. 结果是,helper.js中的subFunc函数在外部可用,而modx.js中的mainFunc在外部可用。

The only object in script A visible from script B is module.exports . 从脚本B可见的脚本A唯一的对象是module.exports Adding objects/functions to module.exports (just like you did it with mainFunc ) makes them visible from the outside. 将对象/功能添加到module.exports (就像使用mainFunc )使它们从外部可见。 There is no other way. 没有别的办法了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM