Node.js 与 WebAssembly
WebAssembly is a high-performance assembly-like language that can be compiled from various languages, including C/C++, Rust, and AssemblyScript. Currently, it is supported by Chrome, Firefox, Safari, Edge, and Node.js!
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
- Module - A compiled WebAssembly binary, ie a
- Memory - A resizable ArrayBuffer.
- Table - A resizable typed array of references not stored in Memory.
- Instance - An instantiation of a Module with its Memory, Table, and variables.
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
There are multiple methods available to generate WebAssembly binary files including:
- Writing WebAssembly (
.wat) by hand and converting to binary format using tools such as wabt
- Using emscripten with a C/C++ application
- Using wasm-pack with a Rust application
- Using AssemblyScript if you prefer a TypeScript-like experience
Once you have a WebAssembly module, you can use the Node.js
WebAssembly object to instantiate it.
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.