好吧,所以我创建了一个测试项目来展示这个错误。错误是Node JS在我的Another对象中找不到我的getStr函数。
这是代码:
var Another = require('./another.js');
var Other = require('./other.js');
var otherStr = Other.getStr();
console.log(otherStr);
var Another = require('./another.js');
var str = Another.getStr();
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函数?
答案 0 :(得分:2)
您在这里处理的是循环依赖。 Node.js将让以循环方式加载模块,但您需要设计代码来解释它。 一般来说,循环依赖表示设计存在一些缺陷。在您在问题中显示的代码中,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
时,another
至少会有getStr
可用。所以这就解决了当前的问题。但请注意,您的other
模块未导出任何内容,因此您的test.js
文件仍会在var otherStr = Other.getStr();
失败,可能您忘记添加此内容:
exports.getStr = function(){
return str;
}
(注意:我已修改了require
来电,因此需要other
而不带.js
后缀。通常,您不希望将后缀添加到您的require
调用。您希望将Node可以解析的模块名称放入文件,包或其他内容。)