node -vnpm -vemcc -v# clang -v# clang -print-targets # ensure wasm32 target existscmake --version# if you use node-gypnode-gyp --version# if you use ninjaninja --version# if you use makemake -v# if you use nmake in Visual Studio Developer Command Promptnmake /?
Build from source
You need to set EMSDK and WASI_SDK_PATH environment variables.
git clone https://github.com/toyobayashi/emnapi.gitcd ./emnapinpm install -g node-gypnpm installnpm run build # output ./packages/*/distnode ./script/release.js # output ./out# testnpm run rebuild:testnpm test
To initialize emnapi, you need to import the emnapi runtime to create a Context by createContext or getDefaultContext first.
Each context owns isolated Node-API object such as napi_env, napi_value, napi_ref. If you have multiple emnapi modules, you should reuse the same Context across them.
declare namespace emnapi { // module '@emnapi/runtime' export class Context { /* ... */ } /** Create a new context */ export function createContext (): Context /** Create or get */ export function getDefaultContext (): Context // ...}
emscripten
then call Module.emnapiInit after emscripten runtime initialized.
Module.emnapiInit only do initialization once, it will always return the same binding exports after successfully initialized.
declare namespace Module { interface EmnapiInitOptions { context: emnapi.Context /** node_api_get_module_file_name */ filename?: string /** * Support following async_hooks related things * on Node.js runtime only * * napi_async_init, * napi_async_destroy, * napi_make_callback, * async resource parameter of * napi_create_async_work and napi_create_threadsafe_function */ nodeBinding?: typeof import('@emnapi/node-binding') /** See Multithread part */ asyncWorkPoolSize?: number } export function emnapiInit (options: EmnapiInitOptions): any}
If you are using Visual Studio Code and have Live Server extension installed, you can right click the HTML file in Visual Studio Code source tree and click Open With Live Server, then you can see the hello world alert!
Compile hello.cpp using em++. C++ exception is disabled by Emscripten default, and not supported by wasi-sdk, so predefine -DNAPI_DISABLE_CPP_EXCEPTIONS and -DNODE_ADDON_API_ENABLE_MAYBE here. If you would like to enable C++ exception, use -sDISABLE_EXCEPTION_CATCHING=0 instead and remove .Check() call. See official documentation here.
If you use node-addon-api, you can use -DEMNAPI_FIND_NODE_ADDON_API=ON or manually add node-addon-api directory to the include dir via include_directories() or target_include_directories().
# Linux or macOSexport GYP_CROSSCOMPILE=1# emscriptenexport AR_target="$EMSDK/upstream/emscripten/emar"export CC_target="$EMSDK/upstream/emscripten/emcc"export CXX_target="$EMSDK/upstream/emscripten/em++"# wasi-sdkexport AR_target="$WASI_SDK_PATH/bin/ar"export CC_target="$WASI_SDK_PATH/bin/clang"export CXX_target="$WASI_SDK_PATH/bin/clang++"
@REM Windowsset GYP_CROSSCOMPILE=1@REM emscriptencall set AR_target=%%EMSDK:\=/%%/upstream/emscripten/emar.batcall set CC_target=%%EMSDK:\=/%%/upstream/emscripten/emcc.batcall set CXX_target=%%EMSDK:\=/%%/upstream/emscripten/em++.bat@REM wasi-sdkcall set AR_target=%%WASI_SDK_PATH:\=/%%/bin/ar.execall set CC_target=%%WASI_SDK_PATH:\=/%%/bin/clang.execall set CXX_target=%%WASI_SDK_PATH:\=/%%/bin/clang++.exe
They are available in emnapi, but you need to know more details before you start to use them.
Now emnapi has 3 implementations of async work and 2 implementations of TSFN:
Async work
A. Libuv threadpool and pthread based implementation in C
B. Single thread mock in JavaScript
C. Web worker based implementation in C (stack allocation) and JavaScript
TSFN
D. Libuv and pthread based implementation in C
E. Web worker based implementation in JavaScript
Library to Link
wasm32-emscripten
wasm32
wasm32-wasi
wasm32-wasi-threads
A
libemnapi-mt.a
✅
❌
❌
✅
B
libemnapi-basic(-mt).a
✅
✅
✅
✅
C
libemnapi-basic-mt.a
❌
✅
❌
✅
D
libemnapi-mt.a
✅
❌
❌
✅
E
libemnapi-basic(-mt).a
✅
✅
✅
✅
There are some limitations on browser about wasi-libc's pthread implementation, for example
pthread_mutex_lock may call __builtin_wasm_memory_atomic_wait32(memory.atomic.wait32)
which is disallowed in browser JS main thread. While Emscripten's pthread implementation
has considered usage in browser. This issue can be solved by upgrading wasi-sdk to v26+
and emnapi v1.5.0+ then pass --export=emnapi_thread_crashed to the linker. If you need to
run your addon with multithreaded features, we recommend you use A & D or C & E.
Note: For browsers, all the multithreaded features relying on Web Workers (Emscripten pthread also relying on Web Workers)
require cross-origin isolation to enable SharedArrayBuffer. You can make a page cross-origin isolated
by serving the page with these headers:
If you would like to avoid SharedArrayBuffer and cross-origin isolation, please use B & E (link against libemnapi-basic.a), see the following table for more details.
About Prebuilt Libraries
Prebuilt libraries can be found in the lib directory in emnapi npm package.
Library
Description
wasm32-emscripten
wasm32
wasm32-wasi
wasm32-wasi-threads
libemnapi.a
no atomics feature.
no libuv port.
napi_*_async_work and napi_*_threadsafe_function always return napi_generic_failure.
✅
✅
✅
✅
libemnapi-mt.a
atomics feature enabled.
napi_*_async_work and napi_*_threadsafe_function are based on pthread and libuv port.
✅
❌
❌
✅
libemnapi-basic.a
no atomics feature.
no libuv port.
napi_*_async_work and napi_*_threadsafe_function are imported from JavaScript land.
✅
✅
✅
✅
libemnapi-basic-mt.a
atomics feature enabled.
no libuv port.
napi_*_async_work and napi_*_threadsafe_function are imported from JavaScript land.
include emnapi_async_worker_create and emnapi_async_worker_init for WebWorker based async work implementation.
This is UV_THREADPOOL_SIZE equivalent at compile time, if not predefined, emnapi will read asyncWorkPoolSize option or UV_THREADPOOL_SIZE from Emscripten environment variable at runtime:
Module.init({ // ... asyncWorkPoolSize: 2})// if asyncWorkPoolSize is not specifiedModule.preRun = Module.preRun || [];Module.preRun.push(function () { if (typeof ENV !== 'undefined') { ENV.UV_THREADPOOL_SIZE = '2'; }});
// wasiinstantiateNapiModule({ // ... asyncWorkPoolSize: 2})// if asyncWorkPoolSize is not specifiednew WASI({ env: { UV_THREADPOOL_SIZE: '2' }})
It represent max of EMNAPI_WORKER_POOL_SIZE async work (napi_queue_async_work) can be executed in parallel. Default is not defined.
You can set both PTHREAD_POOL_SIZE and EMNAPI_WORKER_POOL_SIZE to number of CPU cores in general.
If you use another library function which may create N child threads in async work,
then you need to set PTHREAD_POOL_SIZE to EMNAPI_WORKER_POOL_SIZE * (N + 1).
This option only has effect if you use -pthread.
Emnapi will create EMNAPI_WORKER_POOL_SIZE threads when initializing,
it will throw error if PTHREAD_POOL_SIZE < EMNAPI_WORKER_POOL_SIZE && PTHREAD_POOL_SIZE_STRICT == 2.
This option only has effect if you use -pthread, Default is 0.
Tell emnapi how to delay async work in uv_async_send / uv__async_close.
0: Use setImmediate() (Node.js native setImmediate or browser MessageChannel and port.postMessage)
1: Use Promise.resolve().then()
-DEMNAPI_USE_PROXYING=1
This option only has effect if you use emscripten -pthread. Default is 1 if emscripten version >= 3.1.9, else 0.
0
Use JavaScript implementation to send async work from worker threads, runtime code will access the Emscripten internal PThread object to add custom worker message listener.
1:
Use Emscripten proxying API to send async work from worker threads in C. If you experience something wrong, you can switch set this to 0 and feel free to create an issue.