How to read WebAssembly file it JavaScript from the local file system with native tools

1.9k views Asked by At

I am looking for a way to structure my JavaScript test and read a simple binary WebAssembly file i.e. wasm from the local file system i.e. not in the browser application without using third party tools like node. So far i have found that this can be done with node fs object. but I do not want to load such a huge tool only to read one file. i.e.

I am looking of the way to replace a node call like this

var file = fs.readFileSync('myTestFile.wasm');
var buffer = new Uint8Array(file).buffer;

how will that look like in a JavaScript without node and without browser?

2

There are 2 answers

4
JF Bastien On BEST ANSWER

All JavaScript engines have a non-browser build of their source code which runs on the command line. JSC has jsc, V8 has d8, SpiderMonkey js, and ChakraCore ch.

Those are used by each browser vendor for testing, and inevitably we sometimes need to read ASCII or binary files. There's unfortunately not really a standard for such functionality, but I've found that this works for my purpose:

const readAsBinary = filename => {
if (typeof process === 'object' && typeof require === 'function') {
    const binary = require('fs').readFileSync(file);
    return !binary.buffer ? new Uint8Array(binary) : binary;
} else
    return typeof readbuffer === 'function'
        ? new Uint8Array(readbuffer(file))
        : read(file, 'binary');
};

const instance = new WebAssembly.Instance(new WebAssembly.Module(readAsBinary(filename)), {});

This will only work in node.js or an engine's shell, and not in a browser.

1
murkle On

If you base64-encode the .wasm file then you can include it directly in the JavaScript like this:

Module.wasmBinaryFile = "data:application/wasm;base64,AGFzbQEAAAAByQ/AAWACf38Bf2A...";