node.js eventEmitter : Listen for events across files

空扰寡人 提交于 2019-12-07 18:03:26

You'll want to either pass the server object into your other module like below or you'll want to expose a function on your other module that you can then assign as a listener in the parent module. Either way would work. It just depends where you want the .on call to be.

// app.js

var otherModule = require('./other-module.js');

function onRequest(request, response) {

  var pathname = url.parse(request.url).pathname;
  route(handle, pathname, response);

  console.log("Request for " + pathname + " received.");
}

var server = http.createServer(onRequest);
otherModule.init(server);
server.listen(8888, function () {
  console.log("Server started");
}); // <-- Passing in this callback is a shortcut for defining an event listener for the "listen" event.

// other-module.js

exports.init = function (server) {
  server.on('listen', function () {
    console.log("listen event fired.");
  });
};

In the above example I setup two event listeners for the listen event. The first one is registered when we pass in a callback function to server.listen. That's just a shortcut for doing server.on('listen', ...). The second event handler is setup in other-module.js, obviously :)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!