【问题标题】:What does response.on() method in do in Node js [closed]Node js中的response.on()方法有什么作用[关闭]
【发布时间】:2020-12-19 11:34:24
【问题描述】:

谁能给我描述一下node.js中response.on方法的用途。我习惯了,但不知道它的确切目的是什么。就像我们在学生时代曾经写过 #include 一样,即使我们不知道它究竟是什么,我们也会在每个问题上都写上它,以使其成为一个完美的问题。 ????

【问题讨论】:

标签: javascript node.js https request response


【解决方案1】:

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.ServerResponsestream.Readable 的文档中找到(因为响应也是可读的流)。

【讨论】:

  • 在上面的多个 on() 侦听器中,哪个先发生,或者它们都在它们准备好时发生?
  • @jamespow 当data 事件被发出时,两个监听器按照它们被添加的顺序被执行(所以Received chunk 将首先运行,然后Another listener 一个)。
猜你喜欢
  • 2016-01-04
  • 2016-08-08
  • 1970-01-01
  • 2021-07-25
  • 2011-01-28
  • 1970-01-01
  • 2018-01-24
  • 1970-01-01
  • 2018-05-03
相关资源
最近更新 更多