Temp O'rary
Temp O'rary

Reputation: 5828

How confirm the time when the response has left from NodeJS server?

Problem:
I am doubting that something in my network system is slow which is why responses from NodeJS server arrives late. I've noticed that the server is ready with the response fairly fast however, it takes time to reach the web browser.

Question:
What are the ways I can confirm whether this is infact happening or not? Basically to capture the time when the response left from my NodeJS server and then from the physical server and then compare it with the time that it arrived on the client web browser. How can I do this?

What I tried:
I tried putting a console.log after ctx.body to identify the point of time when the response left the server. But is this the correct point or can I go further down? I am a little unsure. Please advise.

FYI, I am using Koa.js.

Upvotes: 1

Views: 342

Answers (2)

Sebastian Hildebrandt
Sebastian Hildebrandt

Reputation: 2781

As we cannot always assume that the time on the client is exactly the same as on the server, what you theoretically can do is:

  1. client side: before sending a request to the server, get the current time with
const startClient = Date.now()
  1. on the server side you implement a small request time (koa) middleware like this:
app.use(function *(next){
    const startServer = new Date.now();
    await next;
    const ms = (new Date.now()) - startServer;
    ctx.set('X-Server-Time', ms);
});

Place this middleware before defining your routes. This should return a time the server took to complete its task to the client (in the X-Server-Time header). So this is basically the time from when the server receives the request till he is ready and sends results back.

  1. as soon as the client gets back any information from the server, get again the current time and calculate time spend overall:
myHeaders = response.headers;

if (myHeaders[X-Server-Time]) {
    const msServer = parseInt(myHeaders[X-Server-Time]);
    const endClient = Date.now();
    const msOverall = endClient - startClient;

    // output time consumed 
    console.log('Overall time in ms to complete : ' + msOverall);
    console.log('Server time in ms to complete  : ' + msServer);
    console.log('Network time in ms to complete : ' + msOverall - msServer);
}

Code not testet, but I hope this gives an idea how to measure timing...

Upvotes: 2

Adam B
Adam B

Reputation: 1163

Try Koa.js in debug mode and add a logger middleware to identify server side issues.

Use the network inspector in Chrome or any equivalent in other browsers to identify client side issues.

If none of the above helps, you can try debugging on the network level with tcpdump and Wireshark. This helps identifying protocol and connection issues.

Upvotes: 0

Related Questions