The hardware and bandwidth for this mirror is donated by METANET, the Webhosting and Full Service-Cloud Provider.
If you wish to report a bug, or if you are interested in having us mirror your free-software or open-source project, please feel free to contact us at mirror[@]metanet.ch.
A portable, lightweight, zero-dependency JavaScript engine for R, using QuickJS.
Values and objects are directly passed between R and QuickJS, with no need for serialization or deserialization. This both reduces overhead and allows for more complex data structures to be passed between R and JavaScript - including functions.
You can install the development version of QuickJSR from GitHub with:
# install.packages("remotes")
::install_github("andrjohns/QuickJSR") remotes
Or you can install pre-built binaries from R-Universe:
install.packages("QuickJSR", repos = c("https://andrjohns.r-universe.dev",
"https://cran.r-project.org"))
For standalone or simple JavaScript code, you can use the
qjs_eval()
function:
library(QuickJSR)
qjs_eval("1 + 1")
#> [1] 2
qjs_eval("Math.random()")
#> [1] 0.5193045
For more complex interactions, you can create a QuickJS context and evaluate code within that context:
<- JSContext$new() ctx
Use the $source()
method to load JavaScript code into
the context:
# Code can be provided as a string
$source(code = "function add(a, b) { return a + b; }")
ctx
# Or read from a file
<- tempfile(fileext = ".js")
subtract_js writeLines("function subtract(a, b) { return a - b; }", subtract_js)
$source(file = subtract_js) ctx
Then use the $call()
method to call a specified function
with arguments:
$call("add", 1, 2)
ctx#> [1] 3
$call("subtract", 5, 3)
ctx#> [1] 2
As QuickJSR uses the respective C APIs of R and QuickJS to pass values between the two, this allows for more complex data structures to be passed between R and JavaScript.
For example, you can also pass R functions to be evaluated using JavaScript arguments:
$source(code = "function callRFunction(f, x, y) { return f(x, y); }")
ctx$call("callRFunction", function(x, y) x + y, 1, 2)
ctx#> [1] 3
$call("callRFunction", function(x, y) paste0(x, ",", y), "a", "b")
ctx#> [1] "a,b"
You can pass R environments to JavaScript, and both access and update their contents:
<- new.env()
env $x <- 1
env$y <- 2
env
$source(code = "function accessEnv(env) { return env.x + env.y; }")
ctx$call("accessEnv", env)
ctx#> [1] 3
$source(code = "function updateEnv(env) { env.z = env.x * env.y; return env.z;}")
ctx$call("updateEnv", env)
ctx#> [1] 2
$z
env#> [1] 2
QuickJSR also provides a global R
object, which you can
use to access objects and functions from various R packages:
qjs_eval('R.package("base")["Sys.Date"]()')
#> [1] "2024-06-07 03:00:00 EEST"
These binaries (installable software) and packages are in development.
They may not be fully stable and should be used with caution. We make no claims about them.