response.on() 方法在 Node js 中做什么
What does response.on() method in do in Node js
任何人都可以向我描述一下 node.js 中 response.on 方法的用途。我已经习惯了,但不确切知道它的目的是什么。就像我们在学生时代写#include 一样,即使我们不知道它到底是做什么的,我们也会在每个问题上都写上它,以使其成为一个完美的问题。
一个 Node.js HTTP 响应是 EventEmitter
的一个实例,它是一个 class 可以发出事件然后触发该特定事件的所有侦听器。
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 将在响应接收到数据块 chunk
时调用 response.emit('data', chunk)
。发生这种情况时,所有侦听器都将 运行 和 chunk
作为第一个参数。这对于任何其他事件都是一样的。
ServerResponse
的所有事件都可以在 http.ServerResponse
and stream.Readable
的文档中找到(因为响应也是可读流)。
任何人都可以向我描述一下 node.js 中 response.on 方法的用途。我已经习惯了,但不确切知道它的目的是什么。就像我们在学生时代写#include 一样,即使我们不知道它到底是做什么的,我们也会在每个问题上都写上它,以使其成为一个完美的问题。
一个 Node.js HTTP 响应是 EventEmitter
的一个实例,它是一个 class 可以发出事件然后触发该特定事件的所有侦听器。
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 将在响应接收到数据块 chunk
时调用 response.emit('data', chunk)
。发生这种情况时,所有侦听器都将 运行 和 chunk
作为第一个参数。这对于任何其他事件都是一样的。
ServerResponse
的所有事件都可以在 http.ServerResponse
and stream.Readable
的文档中找到(因为响应也是可读流)。