Skip to content

Commit e44ca5e

Browse files
authored
[MODULARIZE=instance] Make output file runnable on node (#24294)
1 parent 701494a commit e44ca5e

File tree

3 files changed

+19
-3
lines changed

3 files changed

+19
-3
lines changed

src/postamble.js

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -300,6 +300,8 @@ function preInit() {
300300
}
301301

302302
#if MODULARIZE == 'instance'
303+
// In MODULARIZE=instance mode we delay most of the initialization work until
304+
// the `init` function is called.
303305
export default async function init(moduleArg = {}) {
304306
Module = moduleArg;
305307
processModuleArgs();
@@ -312,9 +314,21 @@ export default async function init(moduleArg = {}) {
312314
preInit();
313315
run();
314316
}
317+
315318
#if PTHREADS
319+
// When run as a pthread we run `init` immediately.
316320
if (ENVIRONMENT_IS_PTHREAD) await init()
317321
#endif
322+
323+
#if ENVIRONMENT_MAY_BE_NODE
324+
// When run as the main script under node we run `init` immediately.
325+
if (ENVIRONMENT_IS_NODE) {
326+
const url = await import('url');
327+
const isMainModule = url.pathToFileURL(process.argv[1]).href === import.meta.url;
328+
if (isMainModule) await init();
329+
}
330+
#endif
331+
318332
#else
319333
preInit();
320334
run();

test/common.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1398,7 +1398,7 @@ def build(self, filename, libraries=None, includes=None, force_c=False, emcc_arg
13981398
if emcc_args:
13991399
all_emcc_args += emcc_args
14001400
if not output_suffix:
1401-
if '-sEXPORT_ES6' in all_emcc_args or '-sWASM_ESM_INTEGRATION' in all_emcc_args:
1401+
if any(a in all_emcc_args for a in ('-sEXPORT_ES6', '-sWASM_ESM_INTEGRATION', '-sMODULARIZE=instance')):
14021402
output_suffix = '.mjs'
14031403
else:
14041404
output_suffix = '.js'

test/test_core.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6107,8 +6107,7 @@ def test_nl_types(self):
61076107
self.do_core_test('test_nl_types.c')
61086108

61096109
def test_799(self):
6110-
src = test_file('799.cpp')
6111-
self.do_runf(src, '''Set PORT family: 0, port: 3979
6110+
self.do_runf('799.cpp', '''Set PORT family: 0, port: 3979
61126111
Get PORT family: 0
61136112
PORT: 3979
61146113
''')
@@ -9596,6 +9595,9 @@ def test_esm_integration(self):
95969595
self.assertContained('hello, world! (3)', self.run_js('runner.mjs'))
95979596
self.assertFileContents(test_file('core/test_esm_integration.expected.mjs'), read_file('hello_world.mjs'))
95989597

9598+
def test_modularize_instance_hello(self):
9599+
self.do_core_test('test_hello_world.c', emcc_args=['-sMODULARIZE=instance', '-Wno-experimental'])
9600+
95999601
@parameterized({
96009602
'': ([],),
96019603
'pthreads': (['-pthread'],),

0 commit comments

Comments
 (0)