Movatterモバイル変換


[0]ホーム

URL:


Type:Package
Title:Embedded JavaScript and WebAssembly Engine for R
Version:8.0.1
Description:An R interface to V8https://v8.dev: Google's open source JavaScript and WebAssembly engine. This package can be compiled either with V8 or NodeJS when built as a shared library.
License:MIT + file LICENSE
URL:https://jeroen.r-universe.dev/V8
BugReports:https://github.com/jeroen/v8/issues
SystemRequirements:On Linux you can build against libv8-dev (Debian)or v8-devel (Fedora). We also provide static libv8 binaries formost platforms, see the README for details.
NeedsCompilation:yes
VignetteBuilder:knitr
Imports:Rcpp (≥ 0.12.12), jsonlite (≥ 1.0), curl (≥ 1.0), utils
LinkingTo:Rcpp
Suggests:testthat, knitr, rmarkdown
RoxygenNote:7.3.1
Language:en-US
Encoding:UTF-8
Biarch:true
Packaged:2025-10-10 09:30:48 UTC; jeroen
Author:Jeroen OomsORCID iD [aut, cre], George StaggORCID iD [ctb], Jan Marvin Garbuszus [ctb]
Maintainer:Jeroen Ooms <jeroenooms@gmail.com>
Repository:CRAN
Date/Publication:2025-10-10 10:30:20 UTC

Mark character strings as literal JavaScript code

Description

This functionJS() marks character vectors with a special class, sothat it will be treated as literal JavaScript code. It was copied from thehtmlwidgets package, and does exactly the same thing.

Usage

JS(...)

Arguments

...

character vectors as the JavaScript source code (all argumentswill be pasted into one character string)

Author(s)

Yihui Xie

Examples

ct <- v8()ct$eval("1+1")ct$eval(JS("1+1"))ct$assign("test", JS("2+3"))ct$get("test")

Run JavaScript in a V8 context

Description

Thev8() function (formerly callednew_context) creates anew V8context. A context provides an execution environment that allowsseparate, unrelated, JavaScript code to run in a single instance of V8, like atab in a browser.

Usage

v8(global = "global", console = TRUE, ...)engine_info()

Arguments

global

character vector indicating name(s) of the global environment. Use NULL for no name.

console

exposeconsole API (console.log,console.warn,console.error).

...

ignored parameters for past/future versions.

Details

A V8 context cannot be saved or duplicated, but creating a new context and sourcingcode is very cheap. You can run as many parallel v8 contexts as you want. R packagesthat use V8 can use a separate V8 context for each object or function call.

The name of the global object (i.e.global in node andwindowin browsers) can be set with the global argument. A context always have a globalscope, even when no name is set. When a context is initiated withglobal = NULL,the global environment can be reached by evaluatingthis in the global scope,for example:ct$eval("Object.keys(this)").

V8 Context Methods

## ctx <- v8()<V8 engine 13.6.233.17>  $assign(name, value, auto_unbox = TRUE, ...)  $call(fun, ..., auto_unbox = TRUE, await = FALSE, simplify = TRUE)  $console()  $eval(src, serialize = FALSE, await = FALSE)  $get(name, ..., await = FALSE)  $reset()  $source(file)  $validate(src)

Thect$eval method evaluates a string of JavaScript code in the same wayaseval in JavaScript. By defaulteval() returns a string withconsole output; but when theserialize parameter is set toTRUE itserializes the JavaScript return object to a JSON string or a raw buffer.

Thect$get,ct$assign andct$call functions automaticallyconvert arguments and return value between R and JavaScript (using JSON). To passliteral JavaScript arguments that should not be converted to JSON, wrap them inJS(), see examples.

If a call toct$eval(),ct$get(), orct$call() returns a JavaScript promise,you can setawait = TRUE to wait for the promise to be resolved. It will thenreturn the result of the promise, or an error in case the promise is rejected.

Thect$validate function is used to testif a piece of code is valid JavaScript syntax within the context, and alwaysreturns TRUE or FALSE.

In an interactive R session you can usect$console() to switch to aninteractive JavaScript console. Here you can useconsole.log to printobjects, and there is some support for JS tab-completion. This is mostly fortesting and debugging, it may not work perfectly in every IDE or R-frontend.

Data Interchange

JSON is used for data interchange between R and JavaScript. Therefore you can(and should) only exchange data types that have a sensible JSON representation.One exception is raw vectors which are converted to/from Uint8Array buffers, seebelow. All other arguments and objects are automatically converted according to the mappingdescribed inOoms (2014), and implementedby the jsonlite package injsonlite::fromJSON() andjsonlite::toJSON().

As for version 3.0 of this R package, Raw vectors are converted toUint8Arraytyped arrays, and vice versa. This makes it possible to efficiently copy large chunksbinary data between R and JavaScript, which is useful for runningwasmor emscripten.

Note about Linux and Legacy V8 engines

This R package can be compiled against modern (V8 version 6+) libv8 API, or the legacylibv8 API (V8 version 3.15 and below). You can checkV8::engine_info() to see the versionthat is running. The legacy version does not support modern JS (ES6) or WASM, but it isstill the default on older versions of Ubuntu and CentOS. The latest versions of all majorLinux distributions now provide a modern version of V8. For Ubuntu 16.04 and 18.04we provide backports of libv8 (via libnode-dev), see thereadme for details.

References

A Mapping Between JSON Data and R Objects (Ooms, 2014):https://arxiv.org/abs/1403.2805

Examples

# Create a new contextctx <- v8();# Evaluate some codectx$eval("var foo = 123")ctx$eval("var bar = 456")ctx$eval("foo+bar")# Functions and closuresctx$eval("JSON.stringify({x:Math.random()})")ctx$eval("(function(x){return x+1;})(123)")# Objects (via JSON only)ctx$assign("mydata", mtcars)ctx$get("mydata")outlist <- ctx$get("mydata", simplifyVector = FALSE)outlist[1]# Assign JavaScriptctx$assign("foo", JS("function(x){return x*x}"))ctx$assign("bar", JS("foo(9)"))ctx$get("bar")# Validate script without evaluatingctx$validate("function foo(x){2*x}") #TRUEctx$validate("foo = function(x){2*x}") #TRUEctx$validate("function(x){2*x}") #FALSE# Use a JavaScript libraryctx$source("https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.13.6/underscore-min.js")ctx$call("_.filter", mtcars, JS("function(x){return x.mpg < 15}"))# Example from underscore manualctx$eval("_.templateSettings = {interpolate: /\\{\\{(.+?)\\}\\}/g}")ctx$eval("var template = _.template('Hello {{ name }}!')")ctx$call("template", list(name = "Mustache"))# Call anonymous functionctx$call("function(x, y){return x * y}", 123, 3)## Not run: #CoffeeScriptct2 <- v8()ct2$source("http://coffeescript.org/v1/browser-compiler/coffee-script.js")jscode <- ct2$call("CoffeeScript.compile", "square = (x) -> x * x", list(bare = TRUE))ct2$eval(jscode)ct2$call("square", 9)# Interactive consolect3 <- v8()ct3$console()# //this is JavaScript# var test = [1,2,3]# JSON.stringify(test)# exit## End(Not run)

Experimental WebAssembly

Description

Experimental wrapper to load a WebAssembly program. Returns a list ofexported functions. This will probably be moved into it's own packageonce WebAssembly matures.

Usage

wasm(data)wasm_features()

Arguments

data

either raw vector or file path with the binary wasm program

Details

Thewasm_features() function uses thewasm-feature-detectJavaScript library to test which WASM capabilities are supported in thecurrent version of libv8.

Examples

# Load example wasm programinstance <- wasm(system.file('wasm/add.wasm', package = 'V8'))instance$exports$add(12, 30)wasm_features()

[8]ページ先頭

©2009-2025 Movatter.jp