获取从流发送到客户端的数据量
Get amount of data send to client from stream
我有一个 Express API,它具有一些下载功能,通过管道从 fetch
调用到 res
的流来实现。我想记录下载的数据量,以便跟踪帐户使用的数据。我当前的实现是:
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
})
问题在于(我认为)它跟踪从源下载的数据,而没有考虑客户端的带宽限制。比如我下载了一个180MB的文件,但是在客户端取消了20MB的下载,它还是记录了100-180MB。
我如何跟踪客户端实际下载的数据量,而不是 downloaded/buffered 通过 fetch 调用?
您可以尝试“装饰”res.write
函数本身并记录通过那里的字节。类似于:
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);
我有一个 Express API,它具有一些下载功能,通过管道从 fetch
调用到 res
的流来实现。我想记录下载的数据量,以便跟踪帐户使用的数据。我当前的实现是:
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
})
问题在于(我认为)它跟踪从源下载的数据,而没有考虑客户端的带宽限制。比如我下载了一个180MB的文件,但是在客户端取消了20MB的下载,它还是记录了100-180MB。
我如何跟踪客户端实际下载的数据量,而不是 downloaded/buffered 通过 fetch 调用?
您可以尝试“装饰”res.write
函数本身并记录通过那里的字节。类似于:
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);