How to invoke nodejs modules from scala.js?

佐手、 提交于 2019-12-04 11:36:41

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/28656343/how-to-invoke-nodejs-modules-from-scala-js

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