尝试使用Node.js中另一个模块的exports.create

时间:2015-05-27 21:14:25

标签: javascript node.js

我想在另一个模块中使用来自一个模块的代码。

Module1Directory包含以下文件:

Module1.js

exports.create = function(req, res) {
     function something(){}
}

Index.js:

'use strict';

var express = require('express');
var controller = require('./Module1.js');

var router = express.Router();

router.post('/', controller.create);

module.exports = router;

Module2Directory包含以下文件:

Module2.js

var confusing = require('../Module1Directory/Module1.js');

exports.create = function(req, res){
     confusing.create.something();
}

Index.js:

'use strict';

var express = require('express');
var controller = require('./Module2.js');

var router = express.Router();

router.post('/', controller.create);

module.exports = router;

在Module2中运行的函数返回' undefined不是终端中的函数' 。怎么了?

1 个答案:

答案 0 :(得分:2)

您的create功能,但您将其视为非功能对象。您必须调用它,并且必须返回具有something属性的对象:

Module1.js

exports.create = function(req, res) {
     function something(){}

     return {something: something};     // <===
};

Module2.js

var confusing = require('../Module1Directory/Module1.js');

exports.create = function(req, res){
     confusing.create(req, res).something();
     //              ^^^^^^^^^^
};