'TypeError: Failed to execute 'readAsText' on 'FileReader': parameter 1 is not of type 'Blob'

I'm writing an chrome application with scala.js, and have some file reading problem.

When I use chrome.fileSystem.chooseEntry with openDirectory to select a directory, I want to read the _meta_.json file inside, the code is:

chrome.fileSystem.chooseEntry(js.Dynamic.literal("type" -> "openDirectory"), (dir: Entry) => {
    dir.getFile("_meta_.json", js.Dynamic.literal(), (entry: FileEntry) => {
        entry.file((file: FileEntry) => {
          val reader = new FileReader()
          reader.onload = (event: UIEvent) => {
            println("############ read file: " + event)
          }
          reader.onloadend = (event: ProgressEvent) => {
            println("############ read file: " + reader.result)
            ()
          }
          reader.onerror = (event: Event) => {
            println("######### read error")
            ()
          }

          println("###### going to read")
          reader.readAsText(entry.asInstanceOf[Blob]) // !!!!
          ()
        })
    })
})

(The code here is simplified, if you want to see the accurate code, please refer to https://github.com/freewind/fast-links/blob/master/src/main/scala/in/freewind/fastlinks/chrome_app/config/Header.scala#L45)

But when the code is running, it doesn't print anything, seems the file is never read. Then I set a debugger and stepped into the line ends with // !!!!, and run the code in console:

reader.readAsText(this.entry$1$2)

It reports error:

TypeError: Failed to execute 'readAsText' on 'FileReader': parameter 1 is not of type 'Blob'.

It clearly shows the reason, but I don't know how to fix it. I searched but all the similar examples are using the file input file from html DOM.

How to read the file correctly?



Solution 1:[1]

I ran into something similar and found this answer: Problems with HTML5 FileReader

TLDR: The parameter you are passing the file reader is the file name (a string), not the file object itself.

Try something like this :

loadFile: function(e) {
    if(e != undefined) {
      var file = e.target.files[0];
        if(file != null && file.size > 0) {
          reader.readAsText(this.entry$1$2);
          //process file
        } else {
          //error
        }
    }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Community