从这个博客http://blog.mozilla.org/nfroyd/2012/01/26/compressing-strings-in-js/看来应该是可能的,但我在实施时遇到了麻烦(基本上是这样)。
我的代码是
function Accumulator() {
this.buffer = "";
};
Accumulator.prototype = {
buffer: null,
onStartRequest: function(request, context) {},
onStopRequest: function(request, context, statusCode) {},
onDataAvailable: function(request, context, inputStream, offset, count) {
var stream = Components.classes["@mozilla.org/binaryinputstream;1"].createInstance(Components.interfaces.nsIBinaryInputStream);
stream.setInputStream(inputStream);
var input = stream.readByteArray(count);
this.buffer += String.fromCharCode.apply(input);
}
};
function compress(string) {
var accumulator = new Accumulator();
var converter = Components.classes["@mozilla.org/streamconv;1?from=uncompressed&to=gzip"].createInstance(Components.interfaces.nsIStreamConverter);
// More respecifying input/output types.
converter.asyncConvertData("uncompressed", "gzip", accumulator, null);
// Oh, that method doesn't actually convert anything, it just prepares
// the instance for doing conversion.
var stream = Components.classes["@mozilla.org/io/string-input-stream;1"].createInstance(Components.interfaces.nsIStringInputStream);
stream.data = string;
converter.onStartRequest(null, null);
converter.onDataAvailable(null, null, stream, 0, string.length);
converter.onStopRequest(null, null, 201 /* 417 */);
return accumulator.buffer;
};
但是当我使用它时,我收到一个错误,即 converter.onRequestStart 不是函数。
想知道我是否在做明显错误的事情?
编辑:
1)修正一些明显的错误。Ci 原来我没看懂,是 Components.interfaces。
2)原始代码似乎有onRequestStart/Stop倒退,它们应该是onStartRequest/onStopRequest。
通过这些更改,不再引发任何错误,而且还返回一个空字符串,因此似乎没有发生任何事情。:(