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 data
chunks are Buffer
s and they have a .length
property that you can add up.
If you specify the encoding with request.setEncoding()
, your data
chunks will be String
s instead. In that case, call Buffer.byteLength(chunk)
to get the length. (Buffer
is 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:
https.createServer(function(req, res) {
var expected_length = req.headers['content-length']; // I think this is a string ;)
var actual_length = 0;
req.on('data', function (chunk) {
actual_length += chunk.length;
});
req.on('end', function() {
console.log('expected: ' + expected_length + ', actual: ' + actual_length);
});
});
Note: length
refers to the maximum length of the Buffer
'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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With