quickjs.rb
A Ruby wrapper for QuickJS to run JavaScript codes via Ruby with a smaller footprint.
Installation
gem install quickjs
gem 'quickjs'
Usage
Quickjs.eval_code
: Evaluate JavaScript code instantly
require 'quickjs'
Quickjs.eval_code('const fn = (n, pow) => n ** pow; fn(2,8);')
Quickjs.eval_code('const fn = (name) => `Hi, ${name}!`; fn("Itadori");')
Quickjs.eval_code("const isOne = (n) => 1 === n; func(1);")
Quickjs.eval_code("const isOne = (n) => 1 === n; func(3);")
Quickjs.eval_code("[1,2,3]")
Quickjs.eval_code("({ a: '1', b: 1 })")
Quickjs.eval_code("null")
Quickjs.eval_code('const obj = {}; obj.missingKey;')
Quickjs.eval_code("Number('whatever')")
Options
Resources
Quickjs.eval_code(code, { memory_limit: 1024 ** 3 })
Quickjs.eval_code(code, { max_stack_size: 1024 ** 2 })
Built-in modules
To enable std module and os module selectively.
Quickjs.eval_code(code, { features: [Quickjs::MODULE_STD] })
Quickjs.eval_code(code, { features: [Quickjs::MODULE_OS] })
Quickjs.eval_code(code, { features: [Quickjs::FEATURES_TIMEOUT] })
Quickjs::VM
: Maintain a consistent VM/runtime
vm = Quickjs::VM.new
vm.eval_code('const a = { b: "c" };')
vm.eval_code('a.b;')
vm.eval_code('a.b = "d";')
vm.eval_code('a.b;')
Config VM/runtime
Resources
vm = Quickjs::VM.new(
memory_limit: 1024 ** 3,
max_stack_size: 1024 ** 2,
)
Built-in modules
To enable std module and os module selectively.
vm = Quickjs::VM.new(features: [::Quickjs::MODULE_STD])
vm = Quickjs::VM.new(features: [::Quickjs::MODULE_OS])
vm = Quickjs::VM.new(features: [::Quickjs::FEATURES_TIMEOUT])
VM timeout
vm = Quickjs::VM.new(timeout_msec: 1_000)
Quickjs::VM#import
: 🔌 Import ESM from a source code
vm = Quickjs::VM.new
vm.import({ default: 'aliasedDefault', member: 'member' }, from: File.read('exports.esm.js'))
vm.eval_code("aliasedDefault()")
vm.eval_code("member()")
vm.import(['member', 'defaultMember'], from: File.read('exports.esm.js'))
vm.import('DefaultExport', from: File.read('exports.esm.js'))
vm.import('* as all', from: File.read('exports.esm.js'))
Quickjs::VM#define_function
: 💎 Define a global function for JS by Ruby
vm = Quickjs::VM.new
vm.define_function("greetingTo") do |arg1|
['Hello!', arg1].join(' ')
end
vm.eval_code("greetingTo('Rick')")
Quickjs::VM#logs
: 💾 Capture console logs
All logs by console.(log|info|debug|warn|error)
on VM are recorded and inspectable.
vm = Quickjs::VM.new
vm.eval_code('console.log("log me", null)')
vm.logs
vm.logs.last.severity
vm.logs.last.to_s
vm,logs.last.raw
License
Every file in ext/quickjsrb/quickjs
is licensed under the MIT License Copyright 2017-2021 by Fabrice Bellard and Charlie Gordon.
For otherwise, the MIT License, Copyright 2024 by Kengo Hamasaki.