title: Nodejs: content encoding error
body: <p>I have the following Node.js code:</p>
  
  <pre><code>var net = require('net');
  var sys=require('sys');
  
  var reqHash={};
  var resHash={};
  
  var server = net.createServer( function(soc){
  
    soc.on('data', function(data){
      //sys.puts(data);
      var requestData=data;
  
      var conn = net.Socket();
      conn.connect(80,"www.xlhi.com",function(){
         conn.write(data);
      });
      conn.on("connect",function(){
         //sys.puts("connected");
      });
      conn.on("data",function(x){
        var responseData=x.toString();
        //sys.puts(responseData);
        var f=50;
        var toTransmit="";
  
        if(responseData!=undefined){
          var N=responseData.length;
          if(N&gt;f){
            var p=Math.floor(N/f);
            var p_rem=N%f;
  
            var hash="";
            var chunk="";
            for(var i=0;i&lt;p;i++){
              chunk=responseData.substr(f*i,f);
              hash=DJBHash(chunk);
              toTransmit+=chunk;
              if(hash&lt;0){
                hash=hash*-1;
              }
              if(resHash[hash]!=undefined){
                //sys.puts("***Hit"+resHash[hash]);
                //toTransmit=toTransmit+"***EOH"+hash+"EOH***";
              }else{
                resHash[hash]=chunk;
                //toTransmit+=chunk;
              }
            }
            //remainder:
            //toTransmit+="***";
            //sys.puts(f*p+" "+p_rem);
            chunk=responseData.substr(f*p);
            //sys.puts("EOH"+chunk+"\n");
            hash=DJBHash(chunk);
            toTransmit+=chunk;
          }else{
             toTransmit=responseData;
          }
          //sys.puts(x.toString().substr(0,50));
          //sys.puts(toTransmit.substr(0,50));
          sys.puts(toTransmit);
          sys.puts(x);
          soc.write(toTransmit);   /*This line causes content encoding error!*/
        }
      });
    });
  });
  
  server.on('error', function (err){
    // Error processing i just pass whole object
    console.log(err);
  });
  
  server.listen(8080,"172.16.1.218");
  console.log('Server is listening %d\n', 8080);
  
  
  function DJBHash(str) {
    var hash = 5381;
    for(var i = 0; i &lt; str.length; i++) {
      hash = (((hash &lt;&lt; 5) + hash) + str.charCodeAt(i)) &amp; 0xffffffff;
    }
    return hash;
  }
  </code></pre>
  
  <p>Specifically, I'm having trouble with the line marked above. When I change <code>soc.write(toTransmit);</code> to <code>soc.write(x)</code>, everything works fine and I don't get any content encoding errors when I hit refresh in my browser.</p>
  
  <p>As you can see, toTransmit is a chunked version of <code>responseData=x.toString();</code>. I'm guessing I need some way of converting toTransmit into a format suitable for writing to the socket. I don't know how to do this.</p>
  
  <p>Any help greatly appreciated.</p>
  
  <p>Many thanks in advance,</p>