1

我正在尝试在项目中使用 nodejs,并且需要包含一个包含对象的文件。仅仅包含是行不通的。我一直在研究,发现我必须将文件转换为模块。从那里我添加了行“var generator = require('./generator.js');” 到“app.js”和“exports.Generator = new Generator();” 文件包含,但导致此错误:

D:\Users\Miguel Borges\Dropbox\Trabalhos\Lero Lero\nodejs\app.js:14
        var phrase = generator.generatePhrases(1);
                               ^ 
TypeError: Object #<Object> has no method 'generatePhrases'
    at Server.<anonymous> (D:\Users\Miguel Borges\Dropbox\Trabalhos\Lero Lero\nodejs\app.js:14:25)
    at Server.EventEmitter.emit (events.js:91:17)
    at HTTPParser.parser.onIncoming (http.js:1783:12)
    at HTTPParser.parserOnHeadersComplete [as onHeadersComplete] (http.js:111:23)
    at Socket.socket.ondata (http.js:1680:22)
    at TCP.onread (net.js:410:27)

编辑

现在,@Brandon Tilley 的答案是:

D:\Users\Miguel Borges\Dropbox\Trabalhos\Lero Lero\nodejs\app.js:20
console.log(g.Generator.generatePhrases(1));
                        ^
TypeError: Cannot call method 'generatePhrases' of undefined
    at Object.<anonymous> (D:\Users\Miguel Borges\Dropbox\Trabalhos\Lero Lero\nodejs\app.js:20:25)
    at Module._compile (module.js:449:26)
    at Object.Module._extensions..js (module.js:467:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Module.runMain (module.js:492:10)
    at process.startup.processNextTick.process._tickCallback (node.js:244:9)

应用程序.js

var uri = '127.0.0.1';
var port = 8001;

var http = require('http');
var url = require('url');
var g = require('./generator.js');

http.createServer(function (request, response) {
    response.writeHead(200, {'Content-Type': 'text/plain'});

    var path = url.parse(request.url).pathname;
//  var generator = new g.Generator();

    var phrase = g.Generator.generatePhrases(1);

    response.end(path + '\n' + phrase);
}).listen(port, uri);

console.log('Server running at http://' + uri + ':' + port + '/');
console.log(g.Generator.generatePhrases(1));

生成器.js

function Generator () {

}

Generator.prototype.generatePhrases = function(nrPhrases) {
    return 'hi ' + nrPhrases;
};

// exports.Generator = new Generator();
4

1 回答 1

2

你想要module.exports = new Generator()。现在的写法,你需要:

var generator = require('./generator');
generator.Generator.generatePhrases(1);

因为

exports.Generator = new Generator();

说,“当我需要这个模块时,我想要一个对象,它有一个名为 的属性Generator;该属性是 Generator 的一个实例并且有一个generatePhrases方法。”

如果您需要更多关于如何工作的解释,请查看我的模块截屏视频。module.exports

于 2012-08-30T22:46:29.177 回答