A user can POST a document to our web service. We stream it elsewhere. But, at the end of the streaming, we need to be sure they didn’t lie about their Content-Length.
I assume if headerContentLength > realContentLength, the request will just wait for them to send the rest, eventually timing out. So that’s probably OK.
What about if headerContentLength < realContentLength? I.e. what if they keep sending data after they said they were done?
Is this taken care of by Node.js in any way? If not, what is a good way to check? I suppose I could just count up the bytes inside of some data event listeners—i.e., req.on("data", function (chunk) { totalBytes += chunk.length; }). That seems like a kludge though.
To check the actual length of the request, you have to add it up yourself. The
datachunks areBuffers and they have a.lengthproperty that you can add up.If you specify the encoding with
request.setEncoding(), yourdatachunks will beStrings instead. In that case, callBuffer.byteLength(chunk)to get the length. (Bufferis a global object in node.)Add up the total for each of your chunks and you’ll know how much data was sent.
Here’s a rough (untested) example:
Note:
lengthrefers to the maximum length of theBuffer‘s content, not the actual length. However, it works in this case because chunk buffers are always created at the exact correct length. Just be aware of that if you’re working with buffers somewhere else.