Crate: https://crates.io/crates/rustyscript GitHub: https://github.com/rscarson/rustyscript Run JS in rust with deno core

rust-project

Deno is a JS/TS runtime, compatible with Node.js since v2, and written in Rust. In their blog Roll your own JavaScript runtime they demonstrated how to build a custom JS runtime with custom functions using deno_core::op2. I can’t replicate the code in this blog.

This repo make-your-own-js-runtime is a working demo.

rustyscript packaged the into a crate (a thin wrapper over Deno runtime).

Rustyscript is designed to be a thin wrapper over the Deno runtime, to remove potential pitfalls and simplify the API without sacrificing flexibility or performance.

It is used in this tauri demo deno-in-tauri.

The repo also mentions Lavendeux using rustyscript.

I am thinking about building a deno plugin for Tauri. With my kkrpc protocol It should grant Tauri similar power to Electron.

Features

Here are some sample code

Run script in string as a default module

let module = Module::new(
	"test.js",
	"export default (string, integer) => {
		console.log(`Hello world: string=${string}, integer=${integer}`);
		return 4;
	}
	",
);
let value: usize =
    Runtime::execute_module(&module, vec![], Default::default(), json_args!("test", 5))?;
 
assert_eq!(value, 4);

Load script from FS

Modules can also be loaded from the filesystem with [Module::load] or [Module::load_dir] if you want to collect all modules in a given directory.

use rustyscript::{json_args, import};
let mut module = import("js/my_module.js").expect("Something went wrong!");
let value: String = module.call("exported_function_name", json_args!()).expect("Could not get a value!");

Evaluate JS Expression Directly

let result: i64 = rustyscript::evaluate("5 + 5").expect("The expression was invalid!");

Expose Rust Function for JS to Call

use rustyscript::{ Runtime, Module, serde_json::Value };
 
let module = Module::new("test.js", " rustyscript.functions.foo(); ");
let mut runtime = Runtime::new(Default::default())?;
runtime.register_function("foo", |args| {
    if let Some(value) = args.get(0) {
        println!("called with: {}", value);
    }
    Ok(Value::Null)
})?;
runtime.load_module(&module)?;