Reputation: 182
const axios = require("axios");
axios.get('url')
.then(response => {
console.log(response)
})
.catch(err => console.log(err))
How can i measure how much time did it take for website to return full page?
Upvotes: 4
Views: 7266
Reputation: 11
In 2023 (and beyond), a better way is to use the built-in fetch
API which automatically captures request timing measurements. Here's an example:
import { performance } from 'node:perf_hooks';
const url = 'https://jsonplaceholder.typicode.com/posts/1';
const response = await fetch(url);
await response.json();
console.log(performance.getEntriesByName(url));
Outputs:
[
PerformanceResourceTiming {
name: 'https://jsonplaceholder.typicode.com/posts/1',
entryType: 'resource',
startTime: 31.364732027053833,
duration: 764.867231965065,
initiatorType: 'fetch',
nextHopProtocol: undefined,
workerStart: 0,
redirectStart: 0,
redirectEnd: 0,
fetchStart: 31.364732027053833,
domainLookupStart: undefined,
domainLookupEnd: undefined,
connectStart: undefined,
connectEnd: undefined,
secureConnectionStart: undefined,
requestStart: 0,
responseStart: 0,
responseEnd: 796.2319639921188,
transferSize: 300,
encodedBodySize: 0,
decodedBodySize: 0
}
]
The duration
property provides what you're looking for. See https://nodejs.org/api/perf_hooks.html for more details.
Upvotes: 1
Reputation: 2909
You can use performance.now()
to measure the time between starting and finishing the request.
const axios = require("axios");
const { performance } = require('perf_hooks');
let time = performance.now();
axios.get('url')
.then(response => {
console.log(response)
console.log(`${(performance.now() - time) / 1000} seconds`);
})
.catch(err => console.log(err))
Upvotes: 8
Reputation: 12542
Also, You can easily use axios.interceptors
for getting the time at request start and after the response has reached And add it as a part of axios.create
.
For request:
axios.interceptors.request.use(function (config) {
config.timeData = { startTime: new Date()}
return config;
}, function (error) {
return Promise.reject(error);
});
And for response:
axios.interceptors.response.use(function (response) {
response.config.timeData.endTime = new Date()
return response;
}, function (error) {
return Promise.reject(error);
});
You can checkout more on interceptors here
Upvotes: 2