节点JS说的方法显然不存在

时间:2014-05-03 02:51:10

标签: javascript node.js require

好吧,所以我创建了一个测试项目来展示这个错误。错误是Node JS在我的Another对象中找不到我的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函数?

1 个答案:

答案 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可以解析的模块名称放入文件,包或其他内容。)