send_gzip_content.sjs (1673B)
1 function gzipCompressString(string, obs) { 2 let scs = Cc["@mozilla.org/streamConverters;1"].getService( 3 Ci.nsIStreamConverterService 4 ); 5 let listener = Cc["@mozilla.org/network/stream-loader;1"].createInstance( 6 Ci.nsIStreamLoader 7 ); 8 listener.init(obs); 9 let converter = scs.asyncConvertData("uncompressed", "gzip", listener, null); 10 let stringStream = Cc["@mozilla.org/io/string-input-stream;1"].createInstance( 11 Ci.nsIStringInputStream 12 ); 13 // NOTE: This should be setByteStringData, however Android host-utils is 14 // pinned to an old version of xpcom which does not have that method, so 15 // instead we use nsISupportsCString. 16 stringStream.QueryInterface(Ci.nsISupportsCString).data = string; 17 converter.onStartRequest(null, null); 18 converter.onDataAvailable(null, stringStream, 0, string.length); 19 converter.onStopRequest(null, null, null); 20 } 21 22 function produceData() { 23 var chars = 24 "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()_+"; 25 var result = ""; 26 for (var i = 0; i < 100000; ++i) { 27 result += chars; 28 } 29 return result; 30 } 31 32 function handleRequest(request, response) { 33 response.processAsync(); 34 35 // Generate data 36 var strings_to_send = produceData(); 37 response.setHeader("Content-Type", "text/plain", false); 38 response.setHeader("Content-Encoding", "gzip", false); 39 40 let observer = { 41 onStreamComplete(loader, context, status, length, result) { 42 buffer = String.fromCharCode.apply(this, result); 43 response.setHeader("Content-Length", "" + buffer.length, false); 44 response.write(buffer); 45 response.finish(); 46 }, 47 }; 48 gzipCompressString(strings_to_send, observer); 49 }