Introduction: Run your JavaScript on WebAssembly. Javy takes your JavaScript code, and executes it in a WebAssembly embedded JavaScript runtime. Javy can create very small Wasm modules in the 1 to 16 KB range with use of dynamic linking. The default static linking produces modules that are at least 869 KB in size.
Pre-compiled binaries of the Javy CLI can be found on the releases page.
Define your JavaScript like:
// Read input from stdinconstinput=readInput();// Call the function with the inputconstresult=foo(input);// Write the result to stdoutwriteOutput(result);// The main function.functionfoo(input){return{foo: input.n+1,newBar: input.bar+"!"};}// Read input from stdinfunctionreadInput(){constchunkSize=1024;constinputChunks=[];lettotalBytes=0;// Read all the available byteswhile(1){constbuffer=newUint8Array(chunkSize);// Stdin file descriptorconstfd=0;constbytesRead=Javy.IO.readSync(fd,buffer);totalBytes+=bytesRead;if(bytesRead===0){break;}inputChunks.push(buffer.subarray(0,bytesRead));}// Assemble input into a single Uint8Arrayconst{ finalBuffer }=inputChunks.reduce((context,chunk)=>{context.finalBuffer.set(chunk,context.bufferOffset);context.bufferOffset+=chunk.length;returncontext;},{bufferOffset: 0,finalBuffer: newUint8Array(totalBytes)});returnJSON.parse(newTextDecoder().decode(finalBuffer));}// Write output to stdoutfunctionwriteOutput(output){constencodedOutput=newTextEncoder().encode(JSON.stringify(output));constbuffer=newUint8Array(encodedOutput);// Stdout file descriptorconstfd=1;Javy.IO.writeSync(fd,buffer);}Create a WebAssembly binary from your JavaScript by:
javy build index.js -o destination/index.wasmFor more information on the commands you can run javy --help
You can then execute your WebAssembly binary using a WebAssembly engine:
$ echo'{ "n": 2, "bar": "baz" }'| wasmtime index.wasm
{"foo":3,"newBar":"baz!"}% Read the documentation here