Created
April 7, 2023 17:58
-
-
Save Munawwar/c36ab592f381e49fb581ff21c56ad9cd to your computer and use it in GitHub Desktop.
Measure Time to first byte
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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