How to read a resource file in Scala.js?

2019-02-24 01:49发布

Let's say I have a map.csv file at the same level (or some other webapp-accessible place) as index-{dev,opt}.html, e.g.:

key1,value1
key2,value2
...
keyN,valueN

I want to read in that CSV file and end up with a Map[String,String]. I know how to do that in Scala, but how would I do that in Scala.js?

I'm trying not to hard-code the keys and values.

标签: scala.js
1条回答
beautiful°
2楼-- · 2019-02-24 02:06

The parsing is basically identical to how you would do it in conventional Scala -- it's the same language, after all.

So the real issue is fetching the file. There's no one-size-fits-all solution there; it depends on what you're using as the web server, for example. My own system is Play-based, and the cognate code looks like this:

override def postInit() = {
  val ajaxCall:PlayAjax = controllers.Assets.versioned("messages/default/clientStrings")
  ajaxCall.callAjax().map { messageText =>
    val hoconTable = HoconParse(messageText)
    _messages = Some(MessagesImpl("", hoconTable))
    _readyPromise.complete(Success())
  }
}

The details there are particular to my (rather complex) setup, but the basic principle is straightforward: issue an AJAX call to load the file as text, then parse that file.

There are other options as well -- for example, loading and parsing the file server-side, and sending it to the client as strongly-typed structures using something like Autowire. It all depends on what your infrastructure looks like.

查看更多
登录 后发表回答