DenoDDeno
Powered by
Marcus AIreliusM
Denoβ€’3y agoβ€’
14 replies
Marcus AIrelius

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 }
// 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())
}
// 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)
add(1, 2)
from rust?
Deno banner
DenoJoin
Chat about Deno, a modern runtime for JavaScript and TypeScript.
20,934Members
Resources
Recent Announcements

Similar Threads

Was this page helpful?

Similar Threads

Call Rust function from Deno API
thomasmandorferTthomasmandorfer / help
2y ago
rusty_v8 - how to pass data from js/v8 into rust
WereiiWWereii / help
3y ago
How to build WASM from Rust?
vicaryVvicary / help
16mo ago