Skip to content

fix: support --print with --input-type=module #59068

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 24 additions & 5 deletions lib/internal/process/execution.js
Original file line number Diff line number Diff line change
Expand Up @@ -69,12 +69,31 @@ function getEvalModuleUrl() {
* @returns {Promise}
*/
function evalModuleEntryPoint(source, print) {
if (print) {
throw new ERR_EVAL_ESM_CANNOT_PRINT();
}
RegExpPrototypeExec(/^/, ''); // Necessary to reset RegExp statics before user code runs.
RegExpPrototypeExec(/^/, '');

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This has lost a rather important comment.


const actualSource = print
? `export default (async () => (${source}))();`
: source;

return require('internal/modules/run_main').runEntryPointWithESMLoader(
(loader) => loader.eval(source, getEvalModuleUrl(), true),
async (loader) => {
const url = getEvalModuleUrl();
const moduleWrap = loader.createModuleWrap(actualSource, url);

try {
const result = await loader.executeModuleJob(url, moduleWrap, true);

if (print) {
const { log } = require('internal/console/global');
log(result);
}

return result;
} catch (err) {
console.error(err);
process.exitCode = 1;
}
}
);
}

Expand Down
18 changes: 18 additions & 0 deletions test/parallel/test-cli-print-esm.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
'use strict';

const { execSync } = require('child_process');
const assert = require('assert');

const nodeBinary = process.execPath;

try {
const output = execSync(
`${nodeBinary} -p "await Promise.resolve(123)" --input-type=module`
).toString().trim();

assert.strictEqual(output, '123');
console.log('Test passed: ESM --print works with top-level await');
} catch (err) {
console.error('❌ Test failed:', err.stderr?.toString() || err.message);
throw err;
}