Can't fit file encoding when working with Chrome File System API
Asked Answered
P

1

1

I need to read a file which contains a group of symbols moved 65 in ASCII table. It means, for each symbol I am meant to do:

String.fromCharCode('¢'.charCodeAt(0)-65) // returns 'a'

But it is not working at all. I have asked friends of mine to do the test using Python inputting the same file and they got the correct result.

When I try to do the same work with Chrome File System it does not work at all. I can't get back the expected symbols. I think it is a problem with my encoding/charset plataform but I can't figure out what is and how fix it.

I have tried opening the file with other encoding:

var reader=new FileReader();

reader.readAsText(file, 'windows-1252'); // no success
reader.readAsText(file, 'ISO-8859-2'); // no success

Appreciate any help

Partible answered 17/6, 2016 at 15:9 Comment(0)
H
2

Problem is, your shifted text is no longer text by readAsText criteria. Trying to read it with any standard codepage is not going to work.

You should read the file as binary with readAsArrayBuffer(), interpret it as unsigned 8-bit int array, shift the bytes, and then convert the result to string.

var buf = new Uint8Array(reader.readAsArrayBuffer(file));
buf = buf.map((byte) => byte-65);
var string = new TextDecoder("ascii").decode(buf);
Harker answered 17/6, 2016 at 15:45 Comment(4)
Thank you Xan, I will try itPartible
Xan, Am I expected to do the same when writing to a file?Partible
I suppose you could do something similar in reverse (with TextEncoder).Harker
It seems to work with TextEncoder however when I try to input the file content gotten in the readAsArrayBuffer proposed algorithm it brings a Char with the code 129 appended with my letters.Partible

© 2022 - 2024 — McMap. All rights reserved.