最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to run JavaScript code from within Scala (JVM)? - Stack Overflow

programmeradmin0浏览0评论

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.

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.

Share Improve this question asked Apr 21, 2016 at 8:58 DyinDyin 5,3768 gold badges45 silver badges70 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 12

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)

Try to use Rhino or Nashorn it's on Java, but you can use it from Scala

You can use Apache's Common BSF which uses Mozilla Rhino internally.

发布评论

评论列表(0)

  1. 暂无评论