V8 version 0.4: console.log and exception handling

January 13, 2015

V8 version 0.4 has appeared on CRAN. This version introduces several new console functions (console.log, console.warn, console.error) and two vignettes:

I will talk more about using NPM in another blog post this week.

JavaScript Exceptions

Starting V8 version 0.4 each context has a console object in the global namespace:


The console.log, console.warn and console.error functions can be used to generate stdout, warnings or errors in R from JavaScript. This allows for writing embedded JavaScript functions that propagate exceptions back to R, similar as we would do for other foreign language interfaces such as C or C++:

ct <- new_context()
ct$eval('console.log("Bla bla")')
# Bla bla
ct$eval('console.warn("Heads up!")')
# Warning: Heads up!
ct$eval('console.error("Oh noes!")')
# Error: Oh noes!

For example you can use this to verify that external resources were loaded:

ct$eval('var cf = crossfilter || console.error("failed to load crossfilter!")')

Of course, in R you could use tryCatch or whatever you like to catch exceptions that were raised this way in your JavaScript code.

Interactive Console

The interactive console has been enhanced a bit as well. It no longer prints redundant “undefined” returns:

ct <- new_context()
# This is V8 version Press ESC or CTRL+C to exit.

From here we can try our new functions:

console.log("Bla bla")
console.warn("Heads up!")
console.error("Oh noes!")

Bindings to JavaScript Libraries

V8 provides a JavaScript call interface, data interchange, exception handling and interactive debugging console. This is everything we need to embed JavaScript code and libraries in R.

If you are curious how this would work, I have started working on a new R package implementing bindings to some of the very best libraries available for working with JavaScript and HTML. I hope this package will make it’s way to CRAN soon, but until then it is available from github


Some silly example illustrating jshint:

code = "var foo = 123\nvar bar = 456\nfoo + bar"
# var foo = 123
# var bar = 456
# foo + bar

jshint(code)[c("line", "reason")]
#  line                                                                 reason
#     1                                                     Missing semicolon.
#     2                                                     Missing semicolon.
#     3 Expected an assignment or function call and instead saw an expression.
#     3                                                     Missing semicolon.

Or the brilliant uglify-js:

# [1] "var foo=123;var bar=456;foo+bar;"
# Warning: Dropping side-effect-free statement [null:3,0]
# [1] "var foo=123,bar=456;"