Express.JS无法识别所需的js文件的功能

时间:2012-08-10 19:29:10

标签: javascript express

尽管我已经导入了包含我将使用的函数的JS文件,Node.JS表示它未定义。

require('./game_core.js');

Users/dasdasd/Developer/optionalassignment/games.js:28
    thegame.gamecore = new game_core( thegame );
                       ^
ReferenceError: game_core is not defined

你知道什么是错的吗? Game_core包括功能:

var game_core = function(game_instance){....};

3 个答案:

答案 0 :(得分:4)

添加到game_core.js的末尾:

module.exports = {  
    game_core : game_core  
}  

到games.js:

var game_core = require('./game_core').game_core(game_istance);

答案 1 :(得分:2)

要求Node中的模块不会将其内容添加到全局范围。每个模块都包含在自己的范围内,因此您必须export public names

// game_core.js
module.exports = function (game_instance){...};

然后在主脚本中保留对导出对象的引用:

var game_core = require('./game_core.js');
...
thegame.gamecore = new game_core( thegame );

您可以在文档中详细了解它:http://nodejs.org/api/modules.html#modules_modules

答案 2 :(得分:0)

另一种方法:

if( 'undefined' != typeof global ) {
    module.exports = global.game_core = game_core;
}