Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

115
Views
Get amount of data send to client from stream

I've got an Express API which has some download functionality, implemented by piping a stream from a fetch call to res. I want to record the amount of data downloaded, so I can track data used by account. My current implementation is:

let bytesSent = 0
res.set({
  'content-length': contentLength,
  'content-type': contentType,
  'content-disposition': `attachment;filename="${filename}"`,
})

download.body.pipe(res)
download.body.on('data', (chunk) => {
  bytesSent += chunk.byteLength
})
download.body.on('error', next)
res.on('close', async () => {
  // Store bytesSent
})

The problem with this is (I think) it's tracking the data downloaded from source, and not taking into account bandwidth constraints from the client. For example if I download a 180 MB file but cancel the download on the client 20 MB in, it still records 100-180MB.

How can I track the amount of data actually downloaded by the client, rather than downloaded/buffered by the fetch call?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

You could try to "decorate" the res.write function itself and record the bytes passing through there. Something like:

const origResWrite = res.write.bind(res);
res.write = (chunk, encoding, callback) => {
 // Store byteLength of chunk somewhere - here we just log it
 console.log("Writing bytes of size", Buffer.byteLength(chunk));
 origResWrite(chunk, encoding, callback);
}

download.body.pipe(res);
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!