从 JavaScript 打印
fn main() {
js_sandbox::eval_json("console.log('Hello Rust from JS')").expect("JS runs");
}
调用一个JS函数
triple()
一个非常基本的应用程序从 Rust调用一个 JavaScript 函数。它传递一个参数并接受一个返回值,两者都通过 JSON 序列化:
use js_sandbox::{Script, AnyError};
fn main() -> Result<(), AnyError> {
let js_code = "function sub(a, b) { return a - b; }";
let mut script = Script::from_string(js_code)?;
let result: i32 = script.call("sub", (7, 5))?;
assert_eq!(result, 2);
Ok(())
}
序列化 JSON 对象 (Rust -> JS) 并格式化字符串 (JS -> Rust) 的示例:
use js_sandbox::{Script, AnyError};
use serde::Serialize;
#[derive(Serialize)]
struct Person {
name: String,
age: u8,
}
fn main() -> Result<(), AnyError> {
let src = r#"
function toString(person) {
return "A person named " + person.name + " of age " + person.age;
}"#;
let mut script = Script::from_string(src)
.expect("Initialization succeeds");
let person = Person { name: "Roger".to_string(), age: 42 };
let result: String = script.call("toString", (person,)).unwrap();
assert_eq!(result, "A person named Roger of age 42");
Ok(())
}
加载 JS 文件
use js_sandbox::Script;
fn main() {
let mut script = Script::from_file("script.js").expect("Load + init succeeds");
// or, at compile time:
let code: &'static str = include_str!("script.js");
let mut script = Script::from_string(code).expect("Init succeeds");
// use script as usual
}
可以初始化有状态的 JS 脚本,然后使用函数随着时间的推移修改该状态。此示例在两次调用中附加一个字符串,然后在第三次调用中获取结果
use js_sandbox::{Script, AnyError};
fn main() -> Result<(), AnyError> {
let src = r#"
var total = '';
function append(str) { total += str; }
function get() { return total; }"#;
let mut script = Script::from_string(src)?;
let _: () = script.call("append", ("hello",))?;
let _: () = script.call("append", (" world",))?;
let result: String = script.call("get", ())?;
assert_eq!(result, "hello world");
Ok(())
}
使用超时调用脚本
JS 代码可能包含长时间或永远运行的循环,这些循环会阻塞 Rust 代码。可以设置一个超时,之后 JS 脚本执行被中止。
use js_sandbox::{Script, AnyError};
fn main() -> Result<(), AnyError> {
use std::time::Duration;
let js_code = "function run_forever() { for(;;){} }";
let mut script = Script::from_string(js_code)?
.with_timeout(Duration::from_millis(1000));
let result: Result<String, AnyError> = script.call("run_forever", ());
assert_eq!(
result.unwrap_err().to_string(),
"Uncaught Error: execution terminated".to_string()
);
Ok(())
}
将以下内容添加到项目的 Cargo.toml 文件中
[dependencies]
js-sandbox="0.2.0-rc.0"