javascriptrubycommonjsexecjs

How to load pure JS file using ruby gem commonjs?


Simple question: how to load pure .js file from ruby?

My current strategy is to load a .js file from within ruby is to use the commonjs gem. I recognize that the instructions are to load the js directory and then require the file. Unfortunately, I keep getting a TypeError when I try to load the directory for trying to convert nil to string.

Here's my file structure:

.
├── Gemfile
├── LICENSE.md
├── README.md
├── Rakefile
├── lib
│   ├── example
│   │   ├── js
│   │   │   ├── data.json
│   │   │   ├── expressions.js
│   │   │   └── javascript_i_want_to_run.js
│   │   └── version.rb
│   └── example.rb
├── example.gemspec
├── script
└── test

Following the commonjs instructions, here is the failure I get when invoking from pry (notice I'm loading the directory not the file).

[1] pry(main)> require 'commonjs'
=> true
[2] pry(main)> env = CommonJS::Environment.new(path: 'lib/example/js')
TypeError: no implicit conversion of nil into String
from /usr/local/rvm/gems/ruby-2.1.5@rails4/gems/commonjs-0.2.7/lib/commonjs/environment.rb:9:in `initialize'

I'm stumped. Any ideas what could be happening?


Solution

  • There is a mistake in readme. The first parameter in initialize method of CommonJS::Environment class is runtime. It should be:

    require 'commonjs'
    require 'v8'
    
    runtime = V8::Context.new
    env = CommonJS::Environment.new(runtime, path: 'lib/example/js')