Reading source data with Mozilla add-on

I am trying to read and write raw data from files using the Mozilla SDK. I am currently reading data with something like:

function readnsIFile(fileName, callback){
    var nsiFile = new FileUtils.File(fileName);
    NetUtil.asyncFetch(nsiFile, function (inputStream, status) {
        var data = NetUtil.readInputStreamToString(inputStream, inputStream.available(),{charset:"UTF-8"});
        callback(data, status, nsiFile);
    });
}

This works for text files, but when I start messing with raw bytes outside the normal Unicode range, it does not work. For example, if the file contains byte 0xff, then this byte and everything that passed this byte are not read at all. Is there a way to read (and write) raw data using the SDK?

+4
source share
1 answer

You specified explicit charsetin the parameters NetUtil.readInputStream.

charset, . ()

function readnsIFile(fileName, callback){
    var nsiFile = new FileUtils.File(fileName);
    NetUtil.asyncFetch(nsiFile, function (inputStream, status) {
        // Do not specify a charset at all!
        var data = NetUtil.readInputStreamToString(inputStream, inputStream.available());
        callback(data, status, nsiFile);
    });
}

io/byte-streams, , SDK - , ByteReader io/file, , , / . , NetUtil.

, :

const {ByteReader} = require("sdk/io/byte-streams");
function readnsIFile(fileName, callback){
    var nsiFile = new FileUtils.File(fileName);
    NetUtil.asyncFetch(nsiFile, function (inputStream, status) {
        var reader = new ByteReader(inputStream);
        var data = reader.read(inputStream);
        reader.close();
        callback(data, status, nsiFile);
    });
}

, , , , . , , :

  • char () , file.size ( asyncFetch).
  • NetUtil.readInputStreamToString ByteReader char (byte) inputStream, ByteReader 32K , NetUtil.readInputStreamToString file.length.
  • jschar/wchar_t (word) aka. Javascript, .. file.size * 2 .

, 1 , fileSize * 4= 4 (NetUtil.readInputStreamToString) / , fileSize * 3= 3 (ByteReader). 2 , Javascript.

1 , 10 (Firefox Android, Firefox OS), 100 .

ArrayBuffer ( Uint8Array), -, Javascript, NetUtil.readInputStreamToString / ByteReader.

function readnsIFile(fileName, callback){
    var nsiFile = new FileUtils.File(fileName);
    NetUtil.asyncFetch(nsiFile, function (inputStream, status) {
        var bs = Cc["@mozilla.org/binaryinputstream;1"].
            createInstance(Ci.nsIBinaryInputStream);
        bs.setInputStream(inputStream);
        var len = inputStream.available();
        var data = new Uint8Array(len);
        reader.readArrayBuffer(len, data.buffer);
        bs.close();
        callback(data, status, nsiFile);
    });
}

PS: MDN - "iso-8859-1" , charset NetUtil.readInputStreamToString, . .

+5

Source: https://habr.com/ru/post/1541708/


All Articles