js-sandbox
js-sandbox
is a Rust library for executing JavaScript code from Rust in a secure sandbox. It is based on the Deno project and uses serde_json
for serialization.
This library's primary focus is embedding JS as a scripting language into Rust. It does not provide all possible integrations between the two languages, and is not tailored to JS's biggest domain as a client/server side language of the web.
Instead, js-sandbox
focuses on calling standalone JS code from Rust, and tries to remain as simple as possible in doing so.
The typical use case is a core Rust application that integrates with scripts from external users, for example a plugin system or a game that runs
external mods.
This library is in early development, with a basic but powerful API. The API may still evolve considerably.
Examples
Print from JavaScript
The Hello World example -- print something using JavaScript -- is one line, as it should be:
Call a JS function
A very basic application calls a JavaScript function triple()
from Rust. It passes an argument and accepts a return value, both serialized via JSON:
use ;
An example that serializes a JSON object (Rust -> JS) and formats a string (JS -> Rust):
use ;
use Serialize;
Maintain state in JavaScript
It is possible to initialize a stateful JS script, and then use functions to modify that state over time. This example appends a string in two calls, and then gets the result in a third call:
use ;