如何使用scala.js读取文本文件?

时间:2015-05-19 17:31:03

标签: scala scala.js

基本上我正在试图弄清楚我需要传递给onload()方法

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

2 个答案:

答案 0 :(得分:3)

您可以将lambda分配给onload处理程序:

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

答案 1 :(得分:2)

惯用语Scala,错误处理

我不喜欢使用回调,而是喜欢使用模式匹配和map这样:

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 is: $error")
  }

代码:

/** 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
}