通过事件发射器进行 HTTP 分析
在 HTTP 服务器代码中(例如 server.js
):
const EventEmitter = require('events')
const serverEvents = new EventEmitter()
// Set up an HTTP server
const http = require('http')
const httpServer = http.createServer((request, response) => {
// Handler the request...
// Then emit an event about what happened
serverEvents.emit('request', request.method, request.url)
});
// Expose the event emitter
module.exports = serverEvents
在主管代码中(例如 supervisor.js
):
const server = require('./server.js')
// Since the server exported an event emitter, we can listen to it for changes:
server.on('request', (method, url) => {
console.log(`Got a request: ${method} ${url}`)
})
每当服务器收到请求时,它都会发出一个名为 request
的事件,主管正在监听该事件,然后主管可以对事件作出反应。