Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
const {CC, Cu, components} = require('chrome');
const {NetUtil} = Cu.import("resource://gre/modules/NetUtil.jsm");
const {TextReader} = require('sdk/io/file');
const MozFile = CC('@mozilla.org/file/local;1', 'nsILocalFile', 'initWithPath'),
FileInputStream = CC('@mozilla.org/network/file-input-stream;1', 'nsIFileInputStream', 'init'),
StreamLoader = CC('@mozilla.org/network/stream-loader;1', 'nsIStreamLoader', 'init'),
UnicodeConverter = CC('@mozilla.org/intl/scriptableunicodeconverter', 'nsIScriptableUnicodeConverter'),
ConverterInputStream = CC('@mozilla.org/intl/converter-input-stream;1', 'nsIConverterInputStream', 'init'),
InputStreamPump = CC('@mozilla.org/network/input-stream-pump;1', 'nsIInputStreamPump', 'init'),
StringInputStream = CC('@mozilla.org/io/string-input-stream;1', 'nsIStringInputStream');
//https://blog.mozilla.org/nfroyd/2012/01/26/compressing-strings-in-js/
exports.convertStream = function(inStream, from, to, fun) {
let StreamConverter = CC('@mozilla.org/streamconv;1?from=' + from + '&to=' + to, 'nsIStreamConverter');
let streamLoader = new StreamLoader({ onStreamComplete: function(aLoader, aContext, aStatus, aLength, aResult) {
var unicodeConverter = new UnicodeConverter();
unicodeConverter.charset = 'UTF-8';
fun(unicodeConverter.convertFromByteArray(aResult, aLength));
}});
let converter = new StreamConverter();
converter.asyncConvertData(from, to, streamLoader, null);
// converter.onStartRequest(null, null);
// converter.onDataAvailable(null, null, inStream, 0, inStream.available());
// converter.onStopRequest(null, null, 201 /* 417 */); //ErrorListCxxDefines.h
let pump = new InputStreamPump(inStream, -1, -1, 0, 0, true);
pump.asyncRead(streamLoader, null);
};
exports.convertString = function(string, from, to, fun) {
let inStream = new StringInputStream();
inStream.data = string;
exports.convertStream(inStream, from, to, fun);
}
exports.convertFile = function(fileName, from, to, fun) {
NetUtil.asyncFetch(new MozFile(fileName), function(inStream, status) {
//https://developer.mozilla.org/en-US/docs/XPCOM_Interface_Reference/nsIConverterInputStream
exports.convertStream(inStream, from, to, fun);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment