【发布时间】:2020-12-19 11:34:24
【问题描述】:
谁能给我描述一下node.js中response.on方法的用途。我习惯了,但不知道它的确切目的是什么。就像我们在学生时代曾经写过 #include 一样,即使我们不知道它究竟是什么,我们也会在每个问题上都写上它,以使其成为一个完美的问题。 ????
【问题讨论】:
标签: javascript node.js https request response
谁能给我描述一下node.js中response.on方法的用途。我习惯了,但不知道它的确切目的是什么。就像我们在学生时代曾经写过 #include 一样,即使我们不知道它究竟是什么,我们也会在每个问题上都写上它,以使其成为一个完美的问题。 ????
【问题讨论】:
标签: javascript node.js https request response
Node.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 将在响应接收到数据块chunk 时调用response.emit('data', chunk)。发生这种情况时,所有侦听器都将以chunk 作为第一个参数运行。这对于任何其他事件都是一样的。
ServerResponse 的所有事件都可以在 http.ServerResponse 和 stream.Readable 的文档中找到(因为响应也是可读的流)。
【讨论】:
data 事件被发出时,两个监听器按照它们被添加的顺序被执行(所以Received chunk 将首先运行,然后Another listener 一个)。