简体   繁体   English

nodejs http 模块中的 response.write 是否阻塞?

[英]is response.write in nodejs http module blocking?

I see a long wait when I call response.write method of expressjs response object with a big string, like 150 ms.当我用一个大字符串(比如 150 毫秒)调用 expressjs 响应 object 的 response.write 方法时,我看到了漫长的等待。 I am wondering if it is indeed blocking the main thread and how we can avoid that if so.我想知道它是否确实阻塞了主线程,如果是,我们如何避免这种情况。

Note that I cannot use res.send as I write some other chunks in my code later on.请注意,我不能使用 res.send,因为我稍后会在我的代码中编写一些其他块。

Example code:示例代码:

router.get('/*', async (req, res) => {
  const str = "some big string like 256KB"
  res.write(str) // this seems to take 150 ms to go to the next line.
})

res.write() ends up using stream.write() and is not technically blocking. res.write()最终使用stream.write()并且在技术上没有阻塞。 It will not wait until all possible bytes have been sent before returning.它不会等到所有可能的字节都发送完毕后才返回。 It will call the OS to send the first chunk and how long that takes to return may be specific to your OS.它将调用操作系统发送第一个块,返回所需的时间可能特定于您的操作系统。

The return value from res.write() will be false if all the bytes have not yet been sent and it's waiting for the drain event on the stream before it can send the next chunk of data.如果尚未发送所有字节并且它正在等待 ZF7B44CFFAFD5C52223D5498196C8A2E7BZ 上的drain事件,则res.write()的返回值将为false ,然后它才能发送下一个数据块。 The optional callback to res.write() will tell you when all the bytes have been handed off to the OS. res.write()的可选回调将告诉您何时所有字节都已移交给操作系统。

A 150ms time to execute res.write() is odd.执行res.write()的 150 毫秒时间很奇怪。 I manufactured a 10MB string and called res.write() on it and it took 5ms for it to return and 17ms for it to fully send (as indicated by the callback to res.write() ) on my Windows 11 system.我在 Windows 11 系统上制作了一个 10MB 的字符串并在其上调用res.write() ,它返回需要 5 毫秒,完全发送需要 17 毫秒(如res.write()的回调所示)。 Obviously some of this varies by computer, OS and network, but this is nowhere near 150ms.显然,其中一些因计算机、操作系统和网络而异,但这远不及 150 毫秒。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM