Skip to content

Instantly share code, notes, and snippets.

@alinz
Created May 29, 2019 18:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alinz/b7e3cf6101dd2b195decaea12d11a2a4 to your computer and use it in GitHub Desktop.
Save alinz/b7e3cf6101dd2b195decaea12d11a2a4 to your computer and use it in GitHub Desktop.
WebAssembly on Node.js
const { readFileSync } = require("fs");
async function instantiate(source, config) {
const compiled = await WebAssembly.compile(source);
return new WebAssembly.Instance(compiled, config);
}
const config = {
env: {
__memory_base: 0,
__table_base: 0,
memory: new WebAssembly.Memory({
initial: 256,
maximum: 256
}),
table: new WebAssembly.Table({
initial: 0,
element: "anyfunc"
})
}
};
async function main() {
const source = readFileSync("./test.wasm");
const instance = await instantiate(source, config);
console.log(instance.exports._add(9, 9));
console.log(instance.exports._add(9, 19));
console.log(instance.exports._add(9, 29));
console.log(instance.exports._add(9, 39));
}
main();
build:
emcc test.c -O3 -s WASM=1 -s EXPORTED_FUNCTIONS='["_add"]' -s SIDE_MODULE=1 -o test.wasm
run:
node index.js
int add(int a, int b)
{
return a + b;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment