如何从Scala(JVM)运行JavaScript代码?(How to run JavaScript code from within Scala (JVM)?)

编程入门 行业动态 更新时间:2024-10-28 14:27:32
如何从Scala(JVM)运行JavaScript代码?(How to run JavaScript code from within Scala (JVM)?)

是否有任何库允许我们从Scala代码运行JavaScript代码(作为String )? JavaScript代码是运行在JVM中还是派生的JavaScript解释器并不重要。

Is there any library that allows us to run a JavaScript code (as a String) from Scala code? Whether the JavaScript code is running in the JVM or a spawned JavaScript interpreter is not important.

最满意答案

如果您想使用当前的JVM进程,请使用JVM的ScriptEngine 。

import javax.script.ScriptEngineManager val engine = new ScriptEngineManager().getEngineByMimeType("text/javascript") val result = engine.eval("1 + 1") println(result)

这使用JDK 7的Rhino和JDK 8的Nashorn。

Java代码和Nashorn之间的交互是相当无缝的。


如果您想使用新的流程,请使用带有外部JS运行时的ProcessBuilder 。

import java.io.ByteArrayInputStream val input = new ByteArrayInputStream("console.log(1 + 1)".getBytes) val result = ("node" <# input).!! println(result)

如果JS的CPU使用率很高,这可能会让你执行速度最快。 它也允许JS使用Node.js API,但它需要安装Node.js。


如果你想使用当前的JS过程(即如果你使用的是Scala.js ),

import scala.scalajs.js val result = js.eval("1 + 1") println(result)

If you want to use the current JVM process, use JVM's ScriptEngine.

import javax.script.ScriptEngineManager val engine = new ScriptEngineManager().getEngineByMimeType("text/javascript") val result = engine.eval("1 + 1") println(result)

This uses Rhino for JDK 7 and Nashorn for JDK 8.

The interaction between Java code and Nashorn is rather seamless.


If you want to use a new process, use ProcessBuilder with an external JS runtime.

import java.io.ByteArrayInputStream import scala.sys.process._ val input = new ByteArrayInputStream("console.log(1 + 1)".getBytes) val result = ("node" #< input).!! println(result)

This will give you perhaps the fastest execution if the JS is heavy on CPU usage. It also allows the JS to use the Node.js APIs, though it requires Node.js to be installed.


If you want to use the current JS process (i.e. if you are using Scala.js),

import scala.scalajs.js val result = js.eval("1 + 1") println(result)

更多推荐

本文发布于:2023-07-22 06:36:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1217752.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:代码   JVM   Scala   JavaScript   code

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!