Skip to content

Commit

Permalink
Docs: add .mjs example to WebAssembly usage section (#7147)
Browse files Browse the repository at this point in the history
* docs: add .mjs example to WebAssembly usage section

* chore: run prettier

* chore: punctuation nit

---------

Co-authored-by: Michael Esteban <[email protected]>
  • Loading branch information
Makena-Wambui and mikeesto authored Oct 31, 2024
1 parent 90afad3 commit 63e12e7
Showing 1 changed file with 22 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -49,15 +49,36 @@ Once you have a WebAssembly module, you can use the Node.js `WebAssembly` object
// Assume add.wasm file exists that contains a single function adding 2 provided arguments
const fs = require('node:fs');

// Use the readFileSync function to read the contents of the "add.wasm" file
const wasmBuffer = fs.readFileSync('/path/to/add.wasm');

// Use the WebAssembly.instantiate method to instantiate the WebAssembly module
WebAssembly.instantiate(wasmBuffer).then(wasmModule => {
// Exported function live under instance.exports
// Exported function lives under instance.exports object
const { add } = wasmModule.instance.exports;
const sum = add(5, 6);
console.log(sum); // Outputs: 11
});
```

```mjs
// Assume add.wasm file exists that contains a single function adding 2 provided arguments
import fs from 'node:fs/promises';

// Use readFile to read contents of the "add.wasm" file
const wasmBuffer = await fs.readFile('path/to/add.wsm');

// Use the WebAssembly.instantiate method to instantiate the WebAssembly module
const wasmModule = await WebAssembly.instantiate(wasmBuffer);

// Exported function lives under instance.exports object
const { add } = wasmModule.instance.exports;

const sum = add(5, 6);

console.log(sum); // Outputs 11
```

## Interacting with the OS

WebAssembly modules cannot directly access OS functionality on its own. A third-party tool [Wasmtime](https://docs.wasmtime.dev/) can be used to access this functionality. `Wasmtime` utilizes the [WASI](https://wasi.dev/) API to access the OS functionality.
Expand Down

0 comments on commit 63e12e7

Please sign in to comment.