David AlshD
Denoβ€’2y agoβ€’
14 replies
David Alsh

How to call a JS function from Rust?

Hi,

I'd like to call a JS function from Rust but I can't seem to find an example that does so. I got this far with the examples and blog tutorials.

// index.js
function add(a, b) {
  return a + b
}

// Do I need these?
// globalThis.add = add
// export { add }


// main.rs
async fn main_async() {
  let main_module = resolve_path(
    "./index.js",
    env::current_dir().unwrap().join("js").as_path()
  ).unwrap();
  
  let mut js_runtime = JsRuntime::new(RuntimeOptions {
      module_loader: Some(Rc::new(FsModuleLoader)),
      ..Default::default()
  });

  let mod_id = js_runtime.load_main_module(&main_module, None).await.unwrap();

  let result = js_runtime.mod_evaluate(mod_id);
  
  js_runtime.run_event_loop(PollEventLoopOptions::default()).await.unwrap();
  
  result.await.unwrap();
}

fn main() {
  let runtime = tokio::runtime::Builder::new_current_thread()
    .enable_all()
    .build()
    .unwrap();
  runtime.block_on(main_async())
}


How can I call add(1, 2) from rust?
Was this page helpful?