Instantly share code, notes, and snippets.

Embed
What would you like to do?
async function setup() {
// In node, this will use the polyfill and read the file from disk using `fs.readFile('blake2b.wasm', ...)`
// But in the browser, it will make an HTTP fetch request to `GET blake2b.wasm`!
let res = await fetch('blake2b.wasm')
let buf = await res.arrayBuffer()
let mod = await WebAssembly.instantiate(buf))
// ...
}
// A tiny fetch polyfill for node that allows loading external resources in isomorphic libraries.
// Run node code with `-r ./node-fetch` to enable polyfill without needing to change source code.
let { readFile } = require('fs')
global.fetch = fetch
let P = (fn, ...args) => new Promise((resolve, reject) =>
fn(...args, (err, val) => err ? reject(err) : resolve(val)))
async function fetch (path) {
let data = await P(readFile, path)
return {
code: 200,
arrayBuffer
}
async function arrayBuffer () {
return new Uint8Array(data)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment