Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to invoke nodejs modules from scala.js?

I'm trying to use scala.js + nw.js to write some application, and will use some node modules in scala.js. But I'm not sure how to do it.

Say, there is module fs and I can write such code in Javascript:

var fs = require('fs');
fs.writeFile("/tmp/test", "Hey there!", function(err) {
    if(err) {
        console.log(err);
    } else {
        console.log("The file was saved!");
    }
}); 

But how to do the same in scala.js from scratch?

like image 933
Freewind Avatar asked Feb 22 '15 09:02

Freewind


People also ask

Can Scala be compiled to JavaScript?

Scala. js lets you write Scala code that is compiled to JavaScript code that can then be used in the browser. The approach is similar to TypeScript, ReScript, and other languages that are compiled to JavaScript.

Can you use node modules in JavaScript?

Being able to run a node module on the browser is extremely beneficial. Users can use already existing modules on the client side JavaScript application without having to use a server.


1 Answers

Using js.Dynamic and js.DynamicImplits (see also a longer answer on the topic), you can transliterate your code in Scala.js:

import scala.scalajs.js
import js.Dynamic.{global => g}
import js.DynamicImplicits._

val fs = g.require("fs")
fs.writeFile("/tmp/test", "Hey there!", { (err: js.Dynamic) =>
  if (err)
    console.log(err)
  else
    console.log("The file was saved!")
})

You can find a longer source code using the Node.js fs module in Scala.js here: https://github.com/scala-js/scala-js/blob/v0.6.0/tools/js/src/main/scala/org/scalajs/core/tools/io/NodeVirtualFiles.scala

like image 143
sjrd Avatar answered Oct 25 '22 18:10

sjrd