execjs snippets

How to call JavaScript code from Ruby

Tagged execjs, javascript, ruby, therubyracer  Languages js, ruby, javascript


source 'https://rubygems.org'
gem "therubyracer"
# commonjs.rb provides 'require' needed to import modules
gem 'commonjs'


require 'v8'
require 'commonjs'
env = CommonJS::Environment.new(V8::Context.new, path: './node_modules')
env.require('add.js').add(2, 2)


function add(a, b) {
  // Require works, if the package is available in node_modules
  // require('xyz');
  // Console is not available by default
  // console.log(msg);
  return a + b;

exports.add = add;
$ bundle exec ruby add_with_javascript.rb

Tested with:

  • commonjs (0.2.7)
  • libv8 (
  • therubyracer (0.12.3)