node.js eventEmitter:监听文件中的事件 [英] node.js eventEmitter : Listen for events across files
问题描述
刚开始使用Node.js时,我有以下查询:
Just getting started on Node.js, I have the following query:
我的server.js文件中包含以下javascript:
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")
================================================ ================
===============================================================
我还有另一个js文件,我想在其中注册服务器发出的监听"事件或服务器发出的任何事件的侦听器.
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 ?
推荐答案
您将希望像下面那样将服务器对象传递到另一个模块中,或者想要在另一个模块上公开一个函数,然后在父模块中指定为侦听器.无论哪种方式都行得通.这仅取决于您希望.on
调用的位置.
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.");
});
};
在上面的示例中,我为listen
事件设置了两个事件侦听器.当我们将回调函数传递给server.listen
时,第一个被注册.这只是执行server.on('listen', ...)
的快捷方式.第二个事件处理程序显然是在other-module.js中设置的:)
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 :)
这篇关于node.js eventEmitter:监听文件中的事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!