问题
Just getting started on Node.js, I have the following query:
I have a following javascript in my server.js file:
====================================================
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)
server.listen(8888);
console.log("Server started")
===============================================================
I have another js file, where I want to register a listener for the "listening" event emitted by server, or for that matter any event that is emitted by server.
I cannot change the original file to export the server object.
Is there any way I can achieve my objective ?
回答1:
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 :)
来源:https://stackoverflow.com/questions/33832233/node-js-eventemitter-listen-for-events-across-files