joltup / rn-fetch-blob

A project committed to making file access and data transfer easier, efficient for React Native developers.
MIT License
2.81k stars 773 forks source link

Help Reading a UTF-16 Encoded XML File #509

Closed sentry0 closed 4 years ago

sentry0 commented 4 years ago

RN: 0.60.4 RNFB: 0.10.16

Has anyone had any luck reading a UTF-16 encoded file? Here's what I've had to do to get it to work, still losing some characters.

    let data = await RNFetchBlob.fs.readFile(FILE_PATH, 'base64');
    let rawXml = this._decode(data);

   _decode(base64Payload) {
        let buffer = Buffer.from(base64Payload, 'base64');
        let decoded = iconv.decode(buffer, 'utf-16');

        if (decoded.substring(0, 5) !== '<?xml') {
            decoded = iconv.decode(buffer, 'utf-8');
        }

        if (decoded.substring(0, 5) !== '<?xml') {
            throw 'Unable to decode character payload';
        }

        return decoded;
    }
sentry0 commented 4 years ago

This was actually a report I received from a user that turned out to be a a false positive. This technique of reading in UTF-16 encoded files seems to be working fine so far as I can tell.