Introducing V8: An Embedded JavaScript Engine for R
December 17, 2014
JavaScript is an fantastic language for building applications. It runs on browsers, servers and databases, making it possible to design an entire web stack in a single language.
The OpenCPU JavaScript client already allows for calling R functions from JavaScript (see jsfiddles and apps). With the new V8 package we can now do the reverse as well: run JavaScript inside R!
The V8 Engine
V8 is Google’s open source, high performance JavaScript engine. It is written in C++ and implements ECMAScript as specified in ECMA-262, 5th edition. The V8 R package builds on C++ library to provide a completely standalone JavaScript engine within R:
However note that V8 by itself is just the naked JavaScript engine. Currently, there is no DOM, no network or disk IO, not even an event loop. Which is fine because we already have all of those in R. In this sense V8 resembles other foreign language interfaces such as Rcpp or rJava, but then for JavaScript.
A major advantage over the other foreign language interfaces is that V8 requires no compilers, external executables or other run-time dependencies to execute JavaScript. The entire engine is contained within a 6MB R package (2MB when zipped) and works on all major platforms.
Sounds promising? There is more!
V8 + jsonlite = awesome
The native data structure in JavaScript is basically JSON, hence we can use jsonlite for seamless data interchange between V8 and R:
Because jsonlite stores data in its natural structure, we can plug it staight into existing JavaScript libraries:
JavaScript Libraries
JavaScript libraries specifically written for the Browser (such as Jquery or D3) or libraries for Node that depend on disk/network functionality might not work in plain V8, but many of them actually do.
For example, crossfilter is a high performance data filtering library that I have used for creating D3 data dashboards in the browser, but crossfilter itself is just vanilla JavaScript:
I’ll continue here in the next blog post later this week. Have a look at the (very short) package manual in the mean time.