How can I read a text file with scala.js?

£可爱£侵袭症+ 提交于 2019-12-23 00:28:46

问题


Basically I'm trying to figure out what I need to pass to the onload() method

def selectedFile(e: ReactEventI) = {
  val reader = new dom.FileReader()
  reader.readAsText(e.currentTarget.files.item(0))
  reader.onload(
  ) 
}

回答1:


You can assign a lambda to the onload handler:

reader.onload = (e: UIEvent) => {
  // Cast is OK, since we are calling readAsText
  val contents = reader.result.asInstanceOf[String]
  println(contents) 
}



回答2:


Idiomatic Scala, with error handling

Instead of using callbacks, I prefer to work with pattern matching and map like this:

def printFileContent(file: dom.File) =
  readTextFile(file).map {
    case Right(fileContent) => println(s"File content: $fileContent")
    case Left(error) => println(s"Could not read file ${file.name}. Error: $error")
  }

Code:

/** In the future, returns either the file's content or an error,
    if something went wrong */
def readTextFile(fileToRead: dom.File): Future[Either[DOMError, String]] = {

  // Used to create the Future containing either the file content or an error
  val promisedErrorOrContent = Promise[Either[DOMError, String]]

  val reader = new FileReader()
  reader.readAsText(fileToRead, "UTF-8")

  reader.onload = (_: UIEvent) => {
    val resultAsString = s"${reader.result}"
    promisedErrorOrContent.success(Right(resultAsString))
  }
  reader.onerror = (_: Event) => promisedErrorOrContent.success(Left(reader.error))

  promisedErrorOrContent.future
}


来源:https://stackoverflow.com/questions/30332326/how-can-i-read-a-text-file-with-scala-js

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!