THRIFT-2994 Node.js TJSONProtocol cannot be used for object serialization
Client: Node.js
Patch: Tim Sebastian

This closes #379
diff --git a/lib/nodejs/lib/thrift/json_protocol.js b/lib/nodejs/lib/thrift/json_protocol.js
index b98f131..2e0d29a 100644
--- a/lib/nodejs/lib/thrift/json_protocol.js
+++ b/lib/nodejs/lib/thrift/json_protocol.js
@@ -92,9 +92,16 @@
 TJSONProtocol.Version = 1;
 
 TJSONProtocol.prototype.flush = function() {
+  this.writeToTransportIfStackIsFlushable();
   return this.trans.flush();
 };
 
+TJSONProtocol.prototype.writeToTransportIfStackIsFlushable = function() {
+  if (this.tstack.length === 1) {
+    this.trans.write(this.tstack.pop());
+  }
+};
+
 /**
  * Serializes the beginning of a Thrift RPC message.
  * @param {string} name - The service method to call.
@@ -102,9 +109,6 @@
  * @param {number} seqid - The sequence number of this call (always 0 in Apache Thrift).
  */
 TJSONProtocol.prototype.writeMessageBegin = function(name, messageType, seqid) {
-  this.tstack = [];
-  this.tpos = [];
-
   this.tstack.push([TJSONProtocol.Version, '"' + name + '"', messageType, seqid]);
 };
 
@@ -119,6 +123,7 @@
 
   this.wbuf = '[' + this.wobj.join(',') + ']';
 
+  // we assume there is nothing more to come so we write
   this.trans.write(this.wbuf);
 };
 
@@ -151,6 +156,8 @@
 
   str += '}';
   this.tstack[p] = str;
+
+  this.writeToTransportIfStackIsFlushable();
 };
 
 /**
@@ -181,6 +188,8 @@
       fieldInfo.fieldType + ':' + value + '}';
   }
   this.tpos.pop();
+
+  this.writeToTransportIfStackIsFlushable();
 };
 
 /**
@@ -237,6 +246,8 @@
 
   this.tstack[p].push(map);
   this.tstack[p] = '[' + this.tstack[p].join(',') + ']';
+
+  this.writeToTransportIfStackIsFlushable();
 };
 
 /**
@@ -262,6 +273,8 @@
   }
 
   this.tstack[p] = '[' + this.tstack[p].join(',') + ']';
+
+  this.writeToTransportIfStackIsFlushable();
 };
 
 /**
@@ -287,6 +300,8 @@
   }
 
   this.tstack[p] = '[' + this.tstack[p].join(',') + ']';
+
+  this.writeToTransportIfStackIsFlushable();
 };
 
 /** Serializes a boolean */