4

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.

Matthias Braun
  • 32,039
  • 22
  • 142
  • 171
gknauth
  • 2,310
  • 2
  • 29
  • 44

1 Answers1

2

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.

Justin du Coeur
  • 2,699
  • 1
  • 14
  • 19
  • I'm working on a solution based on this. Will let you know when I have it working. Thanks. – gknauth Oct 28 '16 at 14:43
  • So far it's not working, and I've read info that on Chrome you can't use Ajax to access a local file, so I'll have to figure out another way, I think. – gknauth Oct 28 '16 at 16:12
  • Ah -- yes, local files are their own particular bundle of special, and tend to be a nuisance. – Justin du Coeur Oct 28 '16 at 16:58