Node.js中的response.on方法做什么

问题描述

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

解决方法

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)
  })

每当响应接收到response.emit('data',chunk)数据块时,Node.js就会调用chunk。发生这种情况时,所有监听器都将以chunk作为第一个参数运行。其他任何事件都一样。

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