Module object

Module is a global JavaScript object with attributes that Emscripten-generated code calls at various points in its execution.

Developers can provide an implementation ofModule to control the execution of code. For example, to define how notification messages from Emscripten are displayed, developers implement theModule.print attribute.

When an Emscripten application starts up it looks at the values on theModuleobject and applies them. Note that changing the valuesafter startup will notwork in general; in a build withASSERTIONS enabled you will get an errorin that case.

Note

Module is also used to provide access to Emscripten API functions (for exampleccall()) in a safe way. Any function or runtime method exported (usingEXPORTED_FUNCTIONS for compiled functions, orEXPORTED_RUNTIME_METHODS for runtime methods likeccall) will be accessible on theModule object, without minification changing the name, and the optimizer will make sure to keep the function present (and not remove it as unused). See therelevant FAQ entry.

Creating the Module object

Use emcc’spre-js option to add JavaScript code that defines (or extends) theModule object with the behaviour you need.

When generating only JavaScript (as opposed to HTML), noModule object is created by default, and the behaviour is entirely defined by the developer. For example, creating aModule object with the following code will cause all notifications from the program to be calls toalert().

varModule={'print':function(text){alert('stdout: '+text)},'printErr':function(text){alert('stderr: '+text)}};

Important

If you run theClosure Compiler on your code (which is optional, and can be done by--closure1), you will need quotation marks around the properties ofModule as in the example above. In addition, you need to run closure on the compiled code together with the declaration ofModule — this is done automatically for a--pre-js file.

When generating HTML, Emscripten creates aModule object with default methods (seesrc/shell.html). In this case you should again use--pre-js, but this time you add properties to theexistingModule object, for example:

Module['print']=function(text){alert('stdout: '+text)};

Note that once the Module object is received by the main JavaScript file, it will look forModule['print'] and so forth at that time, and use them accordingly. Changing their values later may not be noticed.

Compilation settings

TheINCOMING_MODULE_JS_API compiler setting controls whichModuleattributes are supported in the emitted JS. This list contains commonly-usedthings by default.

Setting this to the smallest possible list for your application will save JScode size. For example, if you use noModule attributes, you can buildwith-sINCOMING_MODULE_JS_API=[]. Or, if you use just a few, you can listthem out, like this:-sINCOMING_MODULE_JS_API=print,printErr.

Affecting execution

The followingModule attributes affect code execution. Set them to customize behavior.

Module.arguments

The commandline arguments. The value ofarguments contains the values returned if compiled code checksargc andargv.

Module.buffer

Allows you to provide your ownArrayBuffer orSharedArrayBuffer to use as the memory.

Note

This is only supported if-sWASM=0. SeeModule.wasmMemory for WebAssembly support.

Module.wasmMemory

Allows you to provide your ownWebAssembly.Memory to use as the memory. The properties used to initialize the memory should match the compiler options.

For example, if you setINITIAL_MEMORY to 8MB without memory growth, then thewasmMemory you provide (if any) should have both the'initial' and'maximum' set to 128 (due to WASM page sizes being 64KB).

Module.locateFile

If set, this method will be called when the runtime needs to load a file, such as a.wasm WebAssembly file,.mem memory init file, or a file generated by the file packager. The function receives the relative path to the file as configured in build process and aprefix (path to the main JavaScript file’s directory), and should return the actual URL. This lets you host file packages or the.mem file etc. on a different location than the directory of the JavaScript file (which is the default expectation), for example if you want to host them on a CDN.

Note

prefix might be an empty string, iflocateFile is called before we load the main JavaScript. For example, that can happen if a file package or a memory initializer file are loaded beforehand (perhaps from the HTML, before it loads the main JavaScript).

Note

SeveralModule.*PrefixURL options have been deprecated in favor oflocateFile, which includesmemoryInitializerPrefixURL,pthreadMainPrefixURL,cdInitializerPrefixURL,filePackagePrefixURL. To update your code, for example if you usedModule.memoryInitializerPrefixURL equal to"https://mycdn.com/memory-init-dir/", then you can replace that with something like:

Module['locateFile']=function(path,prefix){// if it's a mem init file, use a custom dirif(path.endsWith(".mem"))return"https://mycdn.com/memory-init-dir/"+path;// otherwise, use the default, the prefix (JS file's dir) + the pathreturnprefix+path;}
Module.logReadFiles

If set, stderr will log when any file is read.

Module.printWithColors

Controls whether Emscripten runtime libraries try to print with colors. Currently, this only affects sanitizers.

If unset, colors will be enabled if printing to a terminal withnode.

If set totrue, colors will always be used if possible. If set tofalse, colors will never be used.

Module.onAbort

If set, this function is called when abnormal program termination occurs. That can happen due to the C methodabort() being called directly, or called from JavaScript, or due to a fatal problem such as being unable to fetch a necessary file during startup (such as the Wasm binary), etc. After calling this function, program termination occurs (i.e., you can’t use this to try to do something else instead of stopping; there is no possibility of recovering here).

Module.onRuntimeInitialized

If set, this function is called when the runtime is fully initialized, that is, when compiled code is safe to run, which is after any asynchronous startup operations have completed (such as asynchronous WebAssembly compilation, file preloading, etc.). (An alternative to waiting for this to be called is to wait formain() to be called.)

Module.noExitRuntime

IfnoExitRuntime is set totrue, the runtime is not shut down afterrun completes. Shutting down the runtime calls shutdown callbacks, for exampleatexit calls. If you want to continue using the code afterrun() finishes, it is necessary to set this. This is automatically set for you if you use an API command that implies that you want the runtime to not be shut down, for exampleemscripten_set_main_loop.

Module.noInitialRun

IfnoInitialRun is set totrue,main() will not be automatically called (you can do so yourself later). The program will still call global initializers, set up memory initialization, and so forth.

Module.preInit

A function (or array of functions) that must be called before global initializers run, but after basic initialization of the JavaScript runtime. This is typically used forFile System operations.

Module.preinitializedWebGLContext

If building with-sGL_PREINITIALIZED_CONTEXT set, you can setModule.preinitializedWebGLContext to a precreated instance of a WebGL context, which will be used later when initializing WebGL in C/C++ side. Precreating the GL context is useful if doing GL side loading (shader compilation, texture loading etc.) parallel to other page startup actions, and/or for detecting WebGL feature support, such as GL version or compressed texture support up front on a page before or in parallel to loading up any compiled code.

Module.preRun

An array of functions to call right before callingrun(), but after defining and setting up the environment, including global initializers. This is useful, for example, to set up directories and files using theFile System API — as this needs to happen after the FileSystem API has been loaded, but before the program starts to run.

Note

If code needs to affect global initializers, it should instead be run usingpreInit.

Module.print

Called when something is printed to standard output (stdout)

Module.printErr

Called when something is printed to standard error (stderr)

Module.mainScriptUrlOrBlob

Allows pthread workers or WASM workers to independently load up the main application module JavaScript file (e.g. main.js) from a URL or blob. Creation of pthread workers or WASM workers need to load the main application module JavaScript file (e.g. main.js). By default, they load the content of main.js from the URL of main.js. However, if the main.js file was loaded from a Blob, it is not possible to access the URL of the main.js. Also, when main.js is bundled by a Node.JS module bundler (e.g. webpack), the URL of that script can be wrong, the URL after webpack bundler will result in wrong URL like main.chunk.js

Other methods

Module.destroy(obj)

This method should be called to destroy C++ objects created in JavaScript usingWebIDL bindings. If this method is not called, an object may be garbage collected, but its destructor will not be called.

Arguments:
  • obj – The JavaScript-wrapped C++ object to be destroyed.

Module.getPreloadedPackage()

If you want to manually manage the download of .data file packages for custom caching, progress reporting and error handling behavior, you can implement theModule.getPreloadedPackage=function(remotePackageName,remotePackageSize) callback to provide the contents of the data files back to the file loading scripts. The return value of this callback should be an Arraybuffer with the contents of the downloaded file data. See filetest/manual_download_data.html and the testbrowser.test_preload_file_with_manual_data_download for an example.

Module.instantiateWasm()

When targeting WebAssembly, Module.instantiateWasm is an optional user-implemented callback function that the Emscripten runtime calls to perform the WebAssembly instantiation action. The callback function will be called with two parameters,imports andsuccessCallback.imports is a JS object which contains all the function imports that need to be passed to the WebAssembly Module when instantiating, and once instantiated, this callback function should callsuccessCallback() with the generated WebAssembly Instance object.

The instantiation can be performed either synchronously or asynchronously. The return value of this function should contain theexports object of the instantiated WebAssembly Module, or an empty dictionary object{} if the instantiation is performed asynchronously, orfalse if instantiation failed.

Overriding the WebAssembly instantiation procedure via this function is useful when you have other custom asynchronous startup actions or downloads that can be performed in parallel to WebAssembly compilation. Implementing this callback allows performing all of these in parallel. See the filetest/manual_wasm_instantiate.html and the testbrowser.test_manual_wasm_instantiate for an example of how this construct works in action.

Note

Sanitizers or source map is currently not supported if overriding WebAssembly instantiation with Module.instantiateWasm. Providing Module.instantiateWasm when source map or sanitizer is enabled can prevent WebAssembly instantiation from finishing.

Module.fetchSettings()

Override the default settings object used when fetching the Wasm module fromthe network. This attribute is expected to be a string and it defaults to{credentials:'same-origin'}.