Skip to content

Instantly share code, notes, and snippets.

@Munawwar
Created April 7, 2023 17:58
Show Gist options
  • Save Munawwar/c36ab592f381e49fb581ff21c56ad9cd to your computer and use it in GitHub Desktop.
Save Munawwar/c36ab592f381e49fb581ff21c56ad9cd to your computer and use it in GitHub Desktop.
Measure Time to first byte
// time to first byte
const https = require('https');
const http = require('http');
/**
* @param {Object} arg
* @param {String} arg.host
* @param {String} arg.path
* @param {{ [k: string]: string }} arg.headers
*/
module.exports = function httpPing({
isHttps = true,
host,
path,
headers,
}) {
return new Promise((resolve) => {
const start = Date.now();
const req = (isHttps ? https : http).request({
host,
path,
headers,
}, (res) => {
let body = '';
res.once('data', () => {
if (res.statusCode <= 304) {
resolve([Date.now() - start, res.statusCode]);
req.destroy();
}
});
res.on('data', (d) => {
body += d;
});
res.on('end', () => {
resolve([Date.now() - start, res.statusCode, body]);
});
});
req.on('error', (error) => {
resolve([Date.now() - start, -1, error]);
});
req.end();
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment