Search code examples
javascriptrv8

How can I use Javascript library in R language via "V8" packages?


I want to use RiTa.js in R language, but my code does not load the right library. How can I fix it?

Script

library(V8)

ct <- v8()

ct$source("https://cdnjs.cloudflare.com/ajax/libs/rita/1.1.51/rita-full.js")


ct$eval("var s = 'it was a dark and stormy night.';")

ct$eval("var r = new RiString(s);")

Result

Error in context_eval(join(src), private$context) : ReferenceError: RiString is not defined

Solution

  • I think you will just need to make a slight adjustment to get this up and running. The RiTa JavaScript expects to be in the browser with window available. The default in R V8 is global. Fortunately we can easily change with global="window" argument.

    library(V8)
    
    ctx <- v8(global="window")
    ctx$source("https://cdnjs.cloudflare.com/ajax/libs/rita/1.1.51/rita-full.js")
    ctx$get("Object.keys(window)")
    

    You should now see all the RiTa.js available for use.

      [1] "console"      "print"        "window"       "ArrayBuffer" 
      [5] "Int8Array"    "Uint8Array"   "Int16Array"   "Uint16Array" 
      [9] "Int32Array"   "Uint32Array"  "Float32Array" "Float64Array"
     [13] "DataView"     "_RiTa_LTS"    "RiTa"         "RiString"    
     [17] "RiGrammar"    "RiMarkov"     "RiWordNet"    "RiLexicon"   
     [21] "RiTaEvent"