通過事件發射器進行 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
的事件,主管正在監聽該事件,然後主管可以對事件作出反應。