0

我有一个这样的目录结构:

node_modules/mymodule/index.js :

module.exports = require('./lib/mymodule');

node_modules/mymodule/lib/mymodule.js

var A = require('./a'),

function MyModule(){
    var self = this;
    self.version = '0.0.1'; 
}

/**
 * Expose MyModule
 */
module.exports = MyModule;

/**
 * Expose A
 */
exports.A = A;

node_modules/mymodule/lib/a.js

function A(options) {
    console.log('A::constructor()');

};

User.prototype.test = function() {
    return "your test was successful";
};

module.exports = A;

我的问题来自尝试实例化 A。在节点提示中我得到这个:

> var MyModule = require('mymodule');
undefined // why do I get undefined here ?
> var mymodule = new MyModule();
undefined
> var A = MyModule.A;
undefined
> var a = new A();
TypeError: undefined is not a function
    at repl:1:9
    at REPLServer.eval (repl.js:80:21)
    at repl.js:190:20
    at REPLServer.eval (repl.js:87:5)
    at Interface.<anonymous> (repl.js:182:12)
    at Interface.emit (events.js:67:17)
    at Interface._onLine (readline.js:162:10)
    at Interface._line (readline.js:426:8)
    at Interface._ttyWrite (readline.js:603:14)
    at ReadStream.<anonymous> (readline.js:82:12)
4

2 回答 2

0

节点REPL将打印命令的返回值,在所有这些情况下都是未定义的。这并不意味着您的变量未定义。

尝试:

> var A = MyModule.A;

然后

> A
于 2012-04-19T21:50:34.500 回答
0

更改node_modules/mymodule/lib/mymodule.js为:

var exports = module.exports = {
  version: '0.0.1'
}

exports.A = require('./a');

你只能有一个module.exports;)

于 2012-04-19T21:47:02.277 回答