Access JavaScript from Rust
Use JavaScript modules to access the file system, network, databases, and other system resources
This page is outdated. Please visit here to see how to access JavaScript from Rust.
In this tutorial, we will show you how to use the nodejs-helper crate to call Node.js functions from Rust code. Rust functions can now access the file system, network, database, and other system resources from within the WebAssembly container.
The source code of the tutorial is here.
Let's see an example Rust function that gets the system time and prints to the standard output console, all from within a WebAssembly container.
#[wasm_bindgen]
pub fn utc_now() {
let now: String = nodejs_helper::date::utc_string();
nodejs_helper::console::log("UTC time: ");
nodejs_helper::console::log(&now);
}Prerequisite
You must have Node.js installed with the following packages.
$ npm i ssvm sync-request better-sqlite3
$ npm i -g wasm-packIn your Rust application, add the following dependency.
[dependencies]
wasm-bindgen = "=0.2.61"
nodejs-helper = "0.0.3"Building and running
Use the following command to build your Rust application for WebAssembly.
Now, let's look some concrete examples from the example project.
Example: system time and console
The Rust functions to access the system time and console resources are as follows.
The JavaScript code that loads the WebAssembly container and runs the above Rust functions is as follows.
Running the Javascript in Node.js shows the following.
Example: Sqlite database access
The Rust functions to create, update, and query a Sqlite database on the local file system are as follows.
The JavaScript code that loads the WebAssembly container and runs the above Rust functions is as follows.
Running the Javascript in Node.js shows the following.
Example: HTTP network access
The Rust functions to access web services via HTTP/HTTPS and then save content on the local file system are as follows.
The JavaScript code that loads the WebAssembly container and runs the above Rust functions is as follows.
Running the Javascript in Node.js shows the following.
Example: File system access and performance profiler
The Rust functions in this section read an image file from the local file system, resize it, and write back to the file system. It also uses the Javascript console tool to measure the time spent on each task.
The JavaScript code that loads the WebAssembly container and runs the above Rust functions is as follows.
Running the Javascript in Node.js shows the following.
That's it for now. The nodejs-helper crate is still a work-in-progress. We aim to eventually provide Rust APIs for all common system functions here. You are welcome to fork and add to it.
Last updated
Was this helpful?