Class: NodeJS::Environment

Inherits:
Object
  • Object
show all
Defined in:
lib/nodejs/environment.rb

Instance Method Summary collapse

Constructor Details

#initialize(context, base_path) ⇒ Environment

Returns a new instance of Environment.



5
6
7
8
9
10
# File 'lib/nodejs/environment.rb', line 5

def initialize(context, base_path)
  @context = context
  @base_path = Pathname(base_path)
  @cache = {}
  @context.eval("var process = {env: {}}")
end

Instance Method Details

#new_objectObject



12
13
14
# File 'lib/nodejs/environment.rb', line 12

def new_object
  @context['Object'].new
end

#require(module_or_path) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/nodejs/environment.rb', line 16

def require(module_or_path)
  # module main or single js file to require

  return NodeJS.builtins[module_or_path] if NodeJS.builtins[module_or_path]
  
  file = NodeJS.resolve(@base_path.dirname, module_or_path)
  return @cache[file].exports if @cache[file]

  mod = @cache[file] = Module.new(self, file)

  loader = @context.eval("(function(module, require, exports) {#{File.read(file)}});", file.to_s)
  loader.call(mod, mod.require_function, mod.exports)
  mod.exports
end