Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I import a wasm file from a Javascript ES6 file?

How can I use a C++ library after converting it to wasm inside a Node or Vue project? If I understand the concept, wasm can convert native code from C/C++ to Javascript. This means a C++ library can be easily ported and used in an ES6 Javascript file using require() or import, right?

like image 451
newbiedev Avatar asked Oct 28 '25 03:10

newbiedev


1 Answers

you cannot import but if you get the byte format of .wasm file, you can use it inside any javascript file. I will show 2 ways that you can handle:

  • Place the wasm file in public folder and fetch it:

    async function getByte() {

    try {
          const res = await fetch("test.wasm");
          // bytes from memory
          const buffer = await res.arrayBuffer();
          // this will create an object
          const wasm = await WebAssembly.instantiate(buffer);
          console.log(wasm);
          // addTwo function is exported in wasm code, otherwise I would not be able to use it. 
          const addNumbers = wasm.instance.exports.addTwo;
          // console.log(addNumbers);
          const result = addNumbers(10, 50);
          console.log(result);
        } catch (e) {
          console.log(e);
        }
      }
    
  • In linux, xxd command creates a hex dump of a given file or standard input. For example xxd -g1 test.wasm will create the hex format of the wasm.

enter image description here

Now you can use them in javascript file like this:

async function byteCode() {
        const byteArray = new Int8Array([
          0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, 0x01, 0x07, 0x01,
          0x60, 0x02, 0x7f, 0x7f, 0x01, 0x7f, 0x03, 0x02, 0x01, 0x00, 0x07,
          0x07, 0x01, 0x03, 0x73, 0x75, 0x6d, 0x00, 0x00, 0x0a, 0x09, 0x01,
          0x07, 0x00, 0x20, 0x00, 0x20, 0x01, 0x6a, 0x0b, 0x00, 0x18, 0x04,
          0x6e, 0x61, 0x6d, 0x65, 0x01, 0x06, 0x01, 0x00, 0x03, 0x73, 0x75,
          0x6d, 0x02, 0x09, 0x01, 0x00, 0x02, 0x00, 0x01, 0x61, 0x01, 0x01,
          0x62,
        ]);
        // WebAssembly is globally available
        // this will create a javascript object
        const wasm = await WebAssembly.instantiate(byteArray.buffer);
        // you need to know methods in original code
        // in test.wasm I wrote a function and exported as "sum"
        const addNumbers = wasm.instance.exports.sum;
        const result = addNumbers(10, 50);
        console.log(result);
      }
like image 58
Yilmaz Avatar answered Oct 29 '25 18:10

Yilmaz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!