Search code examples
node.jshttpresponse.write

why does response.write block the thread?


Here's the example below:

const http = require('http')
const server = http.createServer()
const log = console.log.bind(console)

server.on('request', (req, res) => {
    log('visited!')
    res.writeHead(200, {
        'Content-Type': 'text/html; charset=utf-8',
    })
    for (let i = 0; i < 100000; i++) {
        res.write('<p>hello</p>')
    }
    res.end('ok')
})


server.listen(3000, '0.0.0.0')

When the server is handling the first request, the thread is blocked and can't handle the second request. I wonder why would this happen since nodejs uses an event-driven, non-blocking I/O model.


Solution

  • Great question.

    NodeJS uses a non-blocking I/O model; that is, I/O operations will run on separate threads under the hood, but all JavaScript code will run on the same event-loop driven thread.

    In your example, when you ask your HTTP server to listen for incoming requests, Node will manage the socket listening operations on a separate thread under the hood so that your code can continue to run after calling server.listen().

    When a request comes, your server.on('request') callback is executed back on the main event-loop thread. If another request comes in, its callback cannot run until the first callback and any other code that is currently executing on the main thread finishes.

    Most of the time, callbacks are short-lived so you rarely need to worry about blocking the main thread. If the callbacks aren't short-lived, they are almost always calling an asynchronous I/O related function that actually does run in a different thread under the hood, therefore freeing up the main thread for other code to execute.