【问题标题】:How to invoke nodejs modules from scala.js?如何从 scala.js 调用 nodejs 模块?
【发布时间】:2023-03-29 08:55:01
【问题描述】:

我正在尝试使用 scala.js + nw.js 编写一些应用程序,并将在 scala.js 中使用一些节点模块。但我不知道该怎么做。

说,有模块fs,我可以用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!");
    }
}); 

但是如何从头开始在 scala.js 中做同样的事情呢?

【问题讨论】:

    标签: node.js scala.js


    【解决方案1】:

    使用js.Dynamicjs.DynamicImplits(另见a longer answer on the topic),您可以在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!")
    })
    

    您可以在此处使用 Scala.js 中的 Node.js fs 模块找到更长的源代码: https://github.com/scala-js/scala-js/blob/v0.6.0/tools/js/src/main/scala/org/scalajs/core/tools/io/NodeVirtualFiles.scala

    【讨论】:

    • 不应该是g.require("fs")吗?
    猜你喜欢
    • 1970-01-01
    • 2017-04-10
    • 1970-01-01
    • 2015-07-15
    • 1970-01-01
    • 1970-01-01
    • 2018-10-29
    • 2013-01-16
    • 1970-01-01
    相关资源
    最近更新 更多