Search code examples
node.jsmethodseventemitter

node.js - Object #<Object> has no method 'on'?


I am so new on node.js. I am trying to fallow EventEmitter samples.

following is my sample code.

var server = require('http'); //var emitter = require('events');

server.createServer(function (req, res) {
  res.writeHead(200, {
    'Content-Type': 'text/plain'
  });

  setTimeout(function () {
    res.end('World\n');
  }, 2000);

  res.write('Hello ');
}).listen(3000, 'localhost');
console.log('Server(port : 3000) is started.');

server.on('connection', function (stream) {
  console.log('Now server is connected.');
});

server.once('connection', function () {
  console.log('The first connection.');
});

var callback = function (stream) {
  console.log('connected...This is callback function.');
};

server.on('connection', callback);
server.removeListener('connection', callback);

I made code like this, since my book says that we can add an event via 'on' method. However, when I run this code it shows error message below.

TypeError: Object #<Object> has no method 'on'
    at Object.<anonymous> (/Users/juneyoungoh/Documents/eventEmiiter.js:16:8)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Function.Module.runMain (module.js:497:10)
    at startup (node.js:119:16)
    at node.js:902:3

I do not know where to find this 'on' method.

Thanks for sharing my problem

Have a great day! :D


Solution

  • require('http'); returns the http module, not your server;

    fix:

    var http = require('http');
    
    var server = http.createServer(  . . . 
    

    The rest works perfectly.