Crate v8 [−] [src]
A high-level wrapper around the V8 Javascript engine.
Usage
First, you need to create an Isolate
. An isolate is a VM
instance with its own heap. You should most likely create one per thread and re-use it as much
as possible.
Then, you need to create a Context
. A context is an execution
environment that allows separate, unrelated, JavaScript code to run in a single instance of V8.
You must explicitly specify the context in which you want any JavaScript code to be run. You
should keep track of the context of a script manually as part of your application.
Example
use v8::{self, value}; // Create a V8 heap let isolate = v8::Isolate::new(); // Create a new context of execution let context = v8::Context::new(&isolate); // Load the source code that we want to evaluate let source = value::String::from_str(&isolate, "'Hello, ' + 'World!'"); // Compile the source code. `unwrap()` panics if the code is invalid, // e.g. if there is a syntax error. let script = v8::Script::compile(&isolate, &context, &source).unwrap(); // Run the compiled script. `unwrap()` panics if the code threw an // exception. let result = script.run(&context).unwrap(); // Convert the result to a value::String. let result_str = result.to_string(&context); // Success! assert_eq!("Hello, World!", result_str.value());
Isolate foreground tasks
Javascript can produce "deferred" or "time-outed" tasks that need to run on the main thread.
Additionally, V8 has a bunch of internal tasks it wants to perform regularly (for example GC).
The user should therefore call isolate.run_enqueued_tasks()
regularly to allow these tasks to
run.
Reexports
pub use context::Context; |
pub use isolate::Isolate; |
pub use script::Script; |
pub use value::Value; |
Modules
context |
Execution contexts and sandboxing. |
error |
Error types and utilities. |
isolate |
Heap and execution isolation. |
script |
Script and source code compilation, execution, origins and management. |
template |
Templates for constructing functions and objects efficiently. |
value |
Javascript values that user code can interact with. |