节点的JS说,方法是不存在的,当它是明确的

好的,所以我创build了一个testing项目来展示这个错误。 错误是节点JS无法在我的另一个对象中find我的getStr函数。

这是代码:

test.js

var Another = require('./another.js'); var Other = require('./other.js'); var otherStr = Other.getStr(); console.log(otherStr); 

other.js

 var Another = require('./another.js'); var str = Another.getStr(); 

another.js

 var Other = require('./other.js'); var str = "other String"; exports.getStr = function(){ return str; } 

这是我的输出:

 C:\Users\Admin\Desktop\JS DEV\NODE DEV\server\test>node test.js C:\Users\Admin\Desktop\JS DEV\NODE DEV\server\test\other.js:3 var str = Another.getStr(); ^ TypeError: Object #<Object> has no method 'getStr' at Object.<anonymous> (C:\Users\Admin\Desktop\JS DEV\NODE DEV\server\test\ot her.js:3:19) at Module._compile (module.js:456:26) at Object.Module._extensions..js (module.js:474:10) at Module.load (module.js:356:32) at Function.Module._load (module.js:312:12) at Module.require (module.js:364:17) at require (module.js:380:17) at Object.<anonymous> (C:\Users\Admin\Desktop\JS DEV\NODE DEV\server\test\an other.js:1:75) at Module._compile (module.js:456:26) at Object.Module._extensions..js (module.js:474:10) C:\Users\Admin\Desktop\JS DEV\NODE DEV\server\test> 

那么如何让Node JS在Other中看到Another的getStr函数呢?

你在这里处理的是循环依赖。 Node.js 会让你以循环的方式加载模块,但你需要devise你的代码来解决它。 一般来说,循环依赖是devise正在遭受一些缺陷的标志。 在问题中显示的代码中, another需要other但是什么也不做。 所以最简单的解决办法是改变another以便不需要other

如果由于某种原因必须保持循环依赖,或者想要为了学习目的而尝试循环依赖,那么这将是另一种可能的解决方法:

 var str = "other String"; exports.getStr = function(){ return str; } var Other = require('./other'); // Actually do something with Other down here. 

other需要时,至less有getStr可用。 所以这照顾了眼前的问题。 但是请注意,你的other模块不会导出任何东西,所以你的test.js文件仍然会失败var otherStr = Other.getStr(); 可能你忘了添加这个:

 exports.getStr = function(){ return str; } 

(注意:我已经修改了require调用,所以它需要other没有.js后缀的文件。一般来说,你不需要在你的require调用中加后缀,你想把一个模块的名称放到一个文件中,一个软件包,或其他东西。)