简体   繁体   中英

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. 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.

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. 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. The optional callback to res.write() will tell you when all the bytes have been handed off to the OS.

A 150ms time to execute res.write() is odd. 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. Obviously some of this varies by computer, OS and network, but this is nowhere near 150ms.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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