Skip to content

Instantly share code, notes, and snippets.

@thinkjrs
Created December 5, 2023 00:46
Show Gist options
  • Save thinkjrs/5d2232d6e3a63ae807125da1d17c4b48 to your computer and use it in GitHub Desktop.
Save thinkjrs/5d2232d6e3a63ae807125da1d17c4b48 to your computer and use it in GitHub Desktop.
Get the response size in TypeScript of a request payload
// https://github.com/vercel/vercel/issues/3825#issuecomment-961295566
function formatBytes(bytes: number, decimals = 2) {
if (bytes === 0) return '0 Bytes'
const k = 1024
const dm = decimals < 0 ? 0 : decimals
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
const i = Math.floor(Math.log(bytes) / Math.log(k))
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i]
}
export function responseSize(payload: any) {
const rs = Buffer.byteLength(JSON.stringify(payload), 'utf-8')
console.log('FINAL Response', rs, formatBytes(rs))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment