response.on() 方法在 Node js 中做什么



任何人都可以向我描述一下node.js中response.on方法的用途。我已经习惯了,但不知道它的目的是什么。就像我们以前在学生时代写 #include 一样,即使我们不知道它到底是什么,我们也会在每个问题上写它,以使其成为一个完美的问题。

一个节点.js HTTP 响应是EventEmitter的一个实例,它是一个可以发出事件然后触发该特定事件的所有侦听器的类。

on方法为特定事件附加一个事件侦听器(函数):

response
.on('data', chunk => {
// This will execute every time the response emits a 'data' event
console.log('Received chunk', chunk)
})
// on returns the object for chaining
.on('data', chunk => {
// You can attach multiple listeners for the same event
console.log('Another listener', chunk)
})
.on('error', error => {
// This one will execute when there is an error
console.error('Error:', error)
})

Node.js 将在响应收到数据块时调用response.emit('data', chunk)chunk.发生这种情况时,所有侦听器都将以chunk作为第一个参数运行。对于任何其他事件也是如此。

ServerResponse的所有事件都可以在http.ServerResponsestream.Readable文档中找到(因为响应也是可读的流)。

最新更新