Node.js 与 WebAssembly
🌐 Node.js with WebAssembly
WebAssembly 是一种高性能、类似汇编的语言,可以由多种语言编译而来,包括 C/C++、Rust 和 AssemblyScript。目前,它受 Chrome、Firefox、Safari、Edge 和 Node.js 支持!
WebAssembly 规范详细说明了两种文件格式,一种是二进制格式,称为 WebAssembly 模块,扩展名为 .wasm,另一种是对应的文本表示,称为 WebAssembly 文本格式,扩展名为 .wat。
🌐 The WebAssembly specification details two file formats, a binary format called a WebAssembly Module with a .wasm extension and corresponding text representation called WebAssembly Text format with a .wat extension.
关键概念
🌐 Key Concepts
- 模块 - 一个已编译的 WebAssembly 二进制文件,即
.wasm文件。 - 内存 - 一个可调整大小的 ArrayBuffer。
- 表 - 一个可调整大小的类型化引用数组,不存储在内存中。
- 实例 - 一个模块的实例化,包含其内存、表和变量。
为了使用 WebAssembly,你需要一个 .wasm 二进制文件以及一套用于与 WebAssembly 通信的 API。Node.js 通过全局的 WebAssembly 对象提供了必要的 API。
🌐 In order to use WebAssembly, you need a .wasm binary file and a set of APIs to communicate with WebAssembly. Node.js provides the necessary APIs via the global WebAssembly object.
.(WebAssembly);
/*
Object [WebAssembly] {
compile: [Function: compile],
validate: [Function: validate],
instantiate: [Function: instantiate]
}
*/
生成 WebAssembly 模块
🌐 Generating WebAssembly Modules
有多种方法可用于生成 WebAssembly 二进制文件,包括:
🌐 There are multiple methods available to generate WebAssembly binary files including:
- 手动编写 WebAssembly(
.wat)并使用诸如 wabt 的工具将其转换为二进制格式 - 在 C/C++ 应用中使用 emscripten
- 在 Rust 应用中使用 wasm-pack
- 如果你更喜欢类似 TypeScript 的体验,可以使用 AssemblyScript
其中一些工具不仅生成二进制文件,还生成 JavaScript “连接”代码以及相应的 HTML 文件,以便在浏览器中运行。
如何使用它
🌐 How to use it
一旦你有了一个 WebAssembly 模块,你可以使用 Node.js 的 WebAssembly 对象来实例化它。
🌐 Once you have a WebAssembly module, you can use the Node.js WebAssembly object to instantiate it.
// Assume add.wasm file exists that contains a single function adding 2 provided arguments
const = ('node:fs');
// Use the readFileSync function to read the contents of the "add.wasm" file
const = .('/path/to/add.wasm');
// Use the WebAssembly.instantiate method to instantiate the WebAssembly module
WebAssembly.().( => {
// Exported function lives under instance.exports object
const { } = ..;
const = (5, 6);
.(); // Outputs: 11
});
与操作系统交互
🌐 Interacting with the OS
WebAssembly 模块本身无法直接访问操作系统功能。可以使用第三方工具 Wasmtime 来访问这些功能。Wasmtime 使用 WASI API 来访问操作系统功能。
🌐 WebAssembly modules cannot directly access OS functionality on its own. A third-party tool Wasmtime can be used to access this functionality. Wasmtime utilizes the WASI API to access the OS functionality.
资源
🌐 Resources