What is the node request event timeout?
Overview
In this shot, we will learn about the request timeout event. This event is fired when the request is idle, or the server takes more time to send a response to the request.
Syntax
request.on('timeout', (res)=>{})
Code
We will write the code to see the working of the request timeout event.
const http = require('http')const port = 8080const server = http.createServer((req,res)=>{setTimeout(()=>{res.end();},2000)});const listener= server.listen(port, () => {console.log(`Server running at port ${port}`)var request = http.request({port: 8080,host: '127.0.0.1',timeout: 1000,});request.end();request.on('timeout', (res)=>{console.log("timeout- server taking too long to respond");})})setTimeout(()=>{server.close()},5000)
Explanation
- Line 1: We import the
HTTPmodule. - Line 3: We define the
portnumber of the server. - Line 5: We use
http.createServer()to create a server and listen to it on port8080. - Line 6: We
setTimeoutof2sec, which means the response will be sent after 2 seconds. Until then, the request will wait. - Line 11: We list to the server using
server.listen(). When the server is running, we make the request in the callback function. - Line 14: We make an http request using
http.request(). It is a get request by default, with parameters defined in options. - Line 17: We defined the timeout for request, so the request will wait for the defined timeout (here
1sec), after which thetimeoutevent will be emitted. - Line 20:
request.end()is important as it finishes the request. If we don’t useend(), the request will be made, but the server will wait for the incoming data untilend()is called. - Line 22: We listen to the
timeoutevent on the request we made. It will be called when the server takes more than thetimeoutdefined for request. - Line 27: We use
setTimeout()because the Educative feature of a running server will not stop until we stop it by callingserver.close(). It will still give you the desired result, but with anexecution timeout error. You don’t need to write this on your personal machine.
Summary
We have played out a situation where the server will take more time to respond to the request.
- Timeout for request is
1000ms (1 sec). - Time taken by server to response is
2000ms (2 sec).
From the above timeout, you can understand that server will take more time to respond, whereas request will wait for less time.
So, when we make the request, the timeout event will be emitted because the server is taking more time to respond, and request can’t wait that long.