[WASM] Run WebAssembly in Node.js using the node-loader
WebAssembly is great for targeting performance bottlenecks in the browser. Now with node-loader, we can do the same on the server through Node.js
While Node offers also bindings to native extensions for C/C++ via node-gyp, there was no straight forward way to write Rust extensions. In addition did the node-gyp API change often and developers had to be careful to make their C/C++ code work with various operating systems.
Compiling Rust to WebAssembly solves both of these issues. The API is stable and once compiled to WebAssembly it will run on every operating system supported by Node.
Since Node doesn't support loading .wasm
files a loader is needed. The loader flag though is only supported when using the --experimental-modules
flag in Node 10 or higher.
Install:
npm i --save @wasm-tool/node
Run:
cargo new crate --name=utils --lib
Cargo.toml:
[package] name = "utils" version = "0.1.0" authors = ["zhentian-wan <answer881215@gmail.com>"] edition = "2018" [lib] crate-type = ["cdylib"] [dependencies]
Build:
cd crate
cargo build --target wasm32-unknown-unknown --release
Create js file:
index.mjs
import { add_one } from "./crate/target/wasm32-unknown-unknown/release/output.wasm" console.log(add_one(1)); console.log(add_one(41));
Run:
node --experimental-modules --loader @wasm-tool/node index.mjs
相关文章
- windows下node.js环境配置
- JS框架_(JQuery.js)上传进度条
- Node.js之Express三
- Node.js之Express二
- Node.js处理I/O数据之Buffer模块缓冲数据
- [Tools] Create a Simple CLI Tool in Node.js with CAC
- [Node.js] Create a model to persist data in a Node.js LoopBack API
- [Node.js] Pass command line arguments to node.js
- [Node.js] Level 3 new. Steam
- node.js原生后台进阶(一)
- [Node.js] Handle Relative Paths in a Node.js ESM Project with import.meta.url
- [Node.js] Load balancing a Http server
- [Node.js] Show More Lines in a Node.js Error Stack Trace
- [Tools] Create a Simple CLI Tool in Node.js with CAC
- [Node.js] Write or Append to a File in Node.js with fs.writeFile and fs.writeFileSync
- [Node.js] Pass command line arguments to node.js
- [Node.js] Use "prestart" in scripts
- [MEAN Stack] First API -- 1. with Node.js, Express and MongoDB
- 如何使用 multiparty 工具库在 Node.js 应用里解析 multipart form-data 格式的请求
- three.js(JS 三维模型库)介绍和入门
- 《node.js开发指南》观后感
- node.js JS对象和JSON字符串之间的转换
- Node.js: node-redis.js客户端
- Node.js:pretty-ms转换毫秒为人类可读的字符串
- mac下使用brew安装node.js环境
- js之选项卡效果(淘宝侧边栏)
- Node.js(二)node 核心模块 fs、HTTP模块、express框架
- Node.js express模块(二)