• Stars
    star
    814
  • Rank 56,027 (Top 2 %)
  • Language
    C
  • License
    Other
  • Created over 7 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A minimal toolkit and runtime to produce and run WebAssembly modules.

webassembly
for node.js

An experimental, minimal toolkit and runtime on top of node to produce and run WebAssembly modules.

To run compiled WebAssembly modules, you'll either need a recent version of your browser with WebAssembly enabled or node.js 8 - but you probably already know that. For development, node.js 6 upwards is sufficient.

npm build status Code Climate npm downloads

Motivation

Prevalent WebAssembly tooling provides compilation to WebAssembly from a C/C++ perspective with a focus on porting existing code. Because of that, it usually produces a lot of extra code that isn't needed alongside a module that is solely trying to complement JavaScript. This package, on the other hand, tries to keep the support library and the generated modules as small as possible by specifically targeting WebAssembly (in the browser) only.

PRs welcome!

Example

Write your module as a C program:

// program.c
#include <webassembly.h>

export int add(int a, int b) {
  return a + b;
}

Compile it to wasm:

$> wa compile -o program.wasm program.c

Run it:

// program.js
require("webassembly")
  .load("program.wasm")
  .then(module => {
    console.log("1 + 2 = " + module.exports.add(1, 2));
  });

Installation

As a dependency:

$> npm install webassembly

OR to use globally with "wa compile":

$> npm install -g webassembly

Installing the package automatically downloads prebuilt binaries for either Windows (win32-x64) or Linux (linux-x64).

Toolkit

WebAssembly functionality is provided by a C header. A small JavaScript support library (distributions) provides the browser runtime.

Calling webassembly.load(file: string, [options: LoadOptions]): Promise<IModule> returns a promise for a module instance:

  • module.exports contains exported functions
  • module.memory references the memory instance
  • module.env references the environment used

Available LoadOptions:

  • imports: Object specifies imported functions
  • initialMemory: number specifies the initial amount of memory in 64k pages (defaults to 1)
  • maximumMemory: number specifies the maximum amount of memory in 64k pages that the module is allowed to grow to (optional)

C features available out of the box:

  • Stripped down standard C library based on musl and dlmalloc
  • import and export defines to mark your imports and exports
  • Browser bindings for console and Math (i.e console.log becomes console_log)

Console functions accept the following string substitutions with variable arguments:

Subst. C type Description
%d, %i int / int32_t Signed 32 bit integer
%u unsigned int / uint32_t Unsigned 32 bit integer
%f float 32 bit float
%lf double 64 bit double
%s char * String (zero terminated)

Browser Math (i.e. Math_sqrt) as well as standard C math.h can be used.

On the JS side of things, the memory instance (module.memory) has additional mixed in utility methods for convenient memory access:

  • memory.getInt(ptr: number): number gets the signed 32 bit integer at the specified address (aligned to 4 bytes)
  • memory.getUint(ptr: number): number gets the unsigned 32 bit integer at the specified address (aligned to 4 bytes)
  • memory.getFloat(ptr: number): number gets the 32 bit float at the specified address (aligned to 4 bytes)
  • memory.getDouble(ptr: number): number gets the 64 bit double at the specified address (aligned to 8 bytes)
  • memory.getString(ptr: number): string gets the zero terminated string literal at the specified address

The underlying typed array views are also available for direct use. Just make sure to access them directly on the memory instance because they are updated when the program memory grows.

  • memory.U8: Uint8Array
  • memory.U32: Uint32Array
  • memory.S32: Int32Array
  • memory.F32: Float32Array
  • memory.F64: Float64Array

Command line

The wa-compile utility (also callable as wa compile, wa comp, wa c) compiles C code to a WebAssembly module.

  -o, --out        Specifies the .wasm output file. Defaults to stdout.
  -d, --debug      Prints debug information to stderr.
  -q, --quiet      Suppresses informatory output.

  Module configuration:

  -O, --optimize   Optimizes the output file and removes dead code.
  -s, --stack      Specifies the stack size. Defaults to 10000.
  -m, --main       Executes the specified function on load.
  -D, --define     Defines a macro.

  Includes and libraries:

  -I, --headers    Includes C headers from the specified directories.
  -i, --include    Includes the specified source files.
  -l, --link       Links in the specified libraries after compilation.
  -b, --bare       Does not include the runtime library.

usage: wa-compile [options] program.c

The wa-link utility (also callable as wa link, wa ln, wa l) linkes multiple WebAssembly modules to one.

  -o, --out      Specifies the .wasm output file. Defaults to write to stdout.
  -d, --debug    Prints debug information to stderr.
  -q, --quiet    Suppresses informatory output.

  Module configuration:

  -O, --optimize   Performs link-time optimizations.

usage: wa-link [options] program1.wasm program2.wasm

The wa-disassemble utility (also callable as wa disassemble, wa dis, wa d) decompiles a WebAssembly module to text format.

  -o, --out      Specifies the .wast output file. Defaults to stdout.
  -d, --debug    Prints debug information to stderr.
  -q, --quiet    Suppresses informatory output.

usage: wa-disassemble [options] program.wasm

The wa-assemble utility (also callable as wa assemble, wa as, wa a) assembles WebAssembly text format to a module.

  -o, --out        Specifies the .wasm output file. Defaults to stdout.
  -d, --debug      Prints debug information to stderr.
  -q, --quiet      Suppresses informatory output.

  Module configuration:

  -O, --optimize   Optimizes the output file and removes dead code.

usage: wa-assemble [options] program.wast

The wa utility proxies to the above, in case you don't like typing -.

Command line utilites can also be used programmatically by providing command line arguments and a callback to their respective main functions:

var compiler = require("webassembly/cli/compiler");
               // or assembler, disassembler, linker
compiler.main([
  "-o", "program.wasm",
  "program.c"
], function(err, filename) {
  if (err)
    throw err;
  console.log("saved to: " + filename);
});

IDE integration

Anything should work as long as you are able to configure it, even notepad.

I am using:


License: MIT License.

Includes parts of

WebAssembly logo by Carlos Baraza (CC0 1.0 Universal).

More Repositories

1

bcrypt.js

Optimized bcrypt in plain JavaScript with zero dependencies.
JavaScript
3,300
star
2

long.js

A Long class for representing a 64-bit two's-complement integer value.
JavaScript
854
star
3

PSON

A super efficient binary serialization format for JSON.
JavaScript
459
star
4

ClosureCompiler.js

Closure Compiler for node.js - the all-round carefree package.
JavaScript
143
star
5

MetaScript

Sophisticated meta programming in JavaScript, e.g. to build different versions of a library from a single source tree.
JavaScript
134
star
6

node.js-closure-compiler-externs

node.js externs for use with Closure Compiler.
JavaScript
76
star
7

Preprocessor.js

A JavaScript source file preprocessor in pure JavaScript, e.g. to build different versions of a library.
JavaScript
70
star
8

node-memcpy

Copies data between node Buffers and/or ArrayBuffers up to ~75 times faster than in pure JS.
JavaScript
54
star
9

utfx

A compact library to encode, decode and convert UTF8 / UTF16 in JavaScript.
JavaScript
53
star
10

btree.js

A ridiculously lean B-tree of variable orders in plain JavaScript.
JavaScript
45
star
11

WebAssembly-prototype

[OUTDATED] JavaScript tools for working with WebAssembly (WASM) binaries.
JavaScript
41
star
12

colour.js

A cored, fixed, documented and optimized version of the popular `colors.js`: Get colors in your node.js console like what...
JavaScript
33
star
13

node-harmonize

Enables --harmony flags programmatically.
JavaScript
25
star
14

BattleCon

A Battlefield / Frostbite engine RCON layer on node.js.
JavaScript
20
star
15

WebRcon

RCON over WebSocket client library and command line interface.
JavaScript
18
star
16

setup-node-nvm

Set up your GitHub Actions workflow with a specific version of node.js using nvm.
JavaScript
16
star
17

grunt-closurecompiler

The ClosureCompiler.js Grunt Task
JavaScript
15
star
18

test.js

A compact testing module for node.js.
JavaScript
14
star
19

dcodeio.github.io

JavaScript
13
star
20

purerc

JavaScript
12
star
21

IntN.js

A library for representing arbitrary byte size integers in JavaScript, both signed and unsigned.
JavaScript
12
star
22

JustMath.js

A rich toolset for two dimensional vector math.
JavaScript
11
star
23

opt.js

Probably the sole command line option parser you'll ever need to...
JavaScript
10
star
24

SharpJS

An embeddable, node.js-like JavaScript environment for Mono and .NET.
C#
10
star
25

lxiv

A compact library to encode and decode base64 data in JavaScript.
JavaScript
10
star
26

___wildcards

A party game for horrible people.
JavaScript
9
star
27

asc-native

AssemblyScript, JavaScript, WebAssembly, C, Binaryen, WABT, Clang, LLVM, CMake, Node.js, Visual Studio and Win32 walk into a bar...
C
9
star
28

ascli

A uniform foundation for unobtrusive (ASCII art in) cli apps.
JavaScript
9
star
29

wapi

A minimal yet viable Web-first Wasm/JS bridge.
TypeScript
7
star
30

quickjs

C
7
star
31

endecrypt

Password based en-/decryption of arbitrary data with and for node.js. http://dcode.io
JavaScript
5
star
32

node-BufferView

A DataView for node Buffers.
JavaScript
5
star
33

FalseSkill

A literal implementation of the Glicko-2 rating system in TypeScript.
JavaScript
4
star
34

doco

A JavaScript Documentation Generator.
JavaScript
4
star
35

PSONSharp

An implementation of Protocol JSON for .NET and Mono.
C#
4
star
36

SourceCon

Simple SRCDS RCON for node.js
JavaScript
3
star
37

BPlusTree.js

Santanu Basu's B+ tree implementation. Streamlined.
JavaScript
3
star
38

esm2umd

Transforms ESM to UMD, i.e. to use ESM by default with UMD as a legacy fallback.
JavaScript
2
star
39

SourceQry

JavaScript
1
star
40

raytrace

TypeScript
1
star
41

Friends

Universal friends plugin for the Oxide modding framework.
C#
1
star
42

llvm.js

C
1
star
43

asext

JavaScript
1
star