4

I am using Cordova File plugin to read a JSON on local filesystem. It works perfectly except for some file where I get an error :

SyntaxError: Unexpected EOF

These files probably have wrong characters and I need to fix them but my problem is not there. My problem is that the plugin logs the error (on the javascript side) but never calls any error callback !!!

When I debug and I follow step by step, on the javascript side I get to the exec() command in FileReader.js, I then follow step by step in objectiveC and it seems perfectly fine, but when ObjectiveC returns it results back with its sendPluginResult, I get this error message in javascript console and no error callback is thrown....

Anybody ever experienced this ? Any idea to catch the error ?

Thank you very much.

2 Answers2

5

I don't know if you solved your problem, but I had a similar issue, which was solved by changing $cordovaFile.readAsText to $cordovaFile.readAsBinaryString, with no other changes. No more EOF problems.

I've hunted the invisible characters, removed newlines and escaped everything possible. Changing the file reader to readAsBinaryString solved the problem.

  • Same here, you saved me, tnx!! – Bruno Laurinec Aug 19 '16 at 14:10
  • 1
    Note that `readAsBinaryString()` will give incorrect results for non-ASCII characters, and is not a general solution to this problem. – NateEag Jul 16 '19 at 14:14
  • @NateEag is correct I am dealing with an issue right now dealing with the 2 $cordovaFile methods mentioned above and readAsBinaryString() causes a lot of issues in some files but not others. – Ju66ernaut Jan 02 '20 at 15:01
  • @Ju66ernaut My answer below should point you in the right direction for working around this problem robustly. – NateEag Jan 02 '20 at 16:44
1

There is a known bug in the Cordova file plugin's readAsText method, which means that files larger than 256 kB containing non-ASCII characters may fail with this error message.

readAsText() reads files in 256 kB chunks. With variable-width encodings like UTF-8, if there's a multibyte character straddling the chunk boundary, then it will be split into two different byte sequences, each of which will be treated as a character.

When the JS environment tries to concatenate the first hunk with such a split character, it sees a byte sequence that's not allowed in a string and throws a SyntaxError.

Since there is no test data attached to this question, I can't be sure this is what happened here, but it seems likely. The symptoms line up.

The GitHub issue I linked above suggests a workaround, which is to use the readAsArrayBuffer() method and to use the browser built-in TextDecoder.decode() method to convert to the correct encoding for your file.

NateEag
  • 575
  • 6
  • 13