I'm trying to use nodejs on a project and needed to include a file that contains an object. the mere inclusion did not work. I've been researching and found that I had to convert the file to a module. from there I added the line "var generator = require('./generator.js');" to "app.js" and "exports.Generator = new Generator ();" to the file includes, but resulted in this error:
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)
now, with answer of @Brandon Tilley thew error is:
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)
app.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));
generator.js
function Generator () {
}
Generator.prototype.generatePhrases = function(nrPhrases) {
return 'hi ' + nrPhrases;
};
// exports.Generator = new Generator();
You want module.exports = new Generator()
. The way it is written now, you'd need:
var generator = require('./generator');
generator.Generator.generatePhrases(1);
Because
exports.Generator = new Generator();
says, "When I require this module, I want an object that has a property called Generator
; that property is an instance of Generator and has a generatePhrases
method."
Take a look at my screencast on modules if you need some more explanation about how module.exports
works.