Avoided sending empty chunkedEncoding chunks in the middle of http responses
authorSam Hughes <sam@samuelhughes.com>
Thu, 29 Apr 2010 02:25:43 +0000 (19:25 -0700)
committerRyan Dahl <ry@tinyclouds.org>
Wed, 26 May 2010 05:58:17 +0000 (22:58 -0700)
lib/http.js
test/simple/test-http-write-empty-string.js [new file with mode: 0644]

index 85b055b..ef2f102 100644 (file)
@@ -392,14 +392,13 @@ OutgoingMessage.prototype.write = function (chunk, encoding) {
 
   encoding = encoding || "ascii";
   if (this.chunkedEncoding) {
-    if (typeof chunk == 'string') {
-      this._send(process._byteLength(chunk, encoding).toString(16));
-    } else {
-      this._send(chunk.length.toString(16));
+    var chunkLength = (typeof chunk == 'string' ? process._byteLength(chunk, encoding) : chunk.length);
+    if (chunkLength > 0) {
+        this._send(chunkLength.toString(16));
+        this._send(CRLF);
+        this._send(chunk, encoding);
+        this._send(CRLF);
     }
-    this._send(CRLF);
-    this._send(chunk, encoding);
-    this._send(CRLF);
   } else {
     this._send(chunk, encoding);
   }
diff --git a/test/simple/test-http-write-empty-string.js b/test/simple/test-http-write-empty-string.js
new file mode 100644 (file)
index 0000000..8a743c6
--- /dev/null
@@ -0,0 +1,40 @@
+PORT = 8000;
+sys = require('sys');
+http = require('http');
+assert = require('assert');
+
+server = http.createServer(function (request, response) {
+  sys.puts('responding to ' + request.url);
+
+  response.writeHead(200, {'Content-Type': 'text/plain'});
+  response.write('1\n');
+  response.write('');
+  response.write('2\n');
+  response.write('');
+  response.end('3\n');
+
+  this.close();
+})
+server.listen(PORT);
+
+var response="";
+
+process.addListener('exit', function () {
+  assert.equal('1\n2\n3\n', response);
+});
+
+
+server.addListener('listening', function () {
+  var client = http.createClient(PORT);
+  var req = client.request("/");
+  req.end();
+  req.addListener('response', function (res) {
+    assert.equal(200, res.statusCode);
+    res.setEncoding("ascii");
+    res.addListener('data', function (chunk) {
+      response += chunk;
+    });
+    sys.error("Got /hello response");
+  });
+});
+