Skip to content

Instantly share code, notes, and snippets.

@creationix
Last active September 5, 2017 21:55
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 creationix/0f2a626bea35d64bb7b1fe5f8036f588 to your computer and use it in GitHub Desktop.
Save creationix/0f2a626bea35d64bb7b1fe5f8036f588 to your computer and use it in GitHub Desktop.
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