Skip to content

Commit c3ed61c

Browse files
committed
Optimize entry point loading by reading file within containsModuleSyntax
1 parent 568a844 commit c3ed61c

File tree

2 files changed

+33
-10
lines changed

2 files changed

+33
-10
lines changed

lib/internal/modules/run_main.js

+2-2
Original file line numberDiff line numberDiff line change
@@ -79,8 +79,8 @@ function shouldUseESMLoader(mainPath) {
7979
return false;
8080
default: { // No package.json or no `type` field.
8181
if (getOptionValue('--experimental-detect-module')) {
82-
const content = fs.readFileSync(mainPath, 'utf8');
83-
return containsModuleSyntax(content, mainPath);
82+
// If the first argument of `containsModuleSyntax` is undefined, it will read `mainPath` from the file system.
83+
return containsModuleSyntax(undefined, mainPath);
8484
}
8585
return false;
8686
}

src/node_contextify.cc

+31-8
Original file line numberDiff line numberDiff line change
@@ -1384,20 +1384,43 @@ constexpr std::array<std::string_view, 3> esm_syntax_error_messages = {
13841384

13851385
void ContextifyContext::ContainsModuleSyntax(
13861386
const FunctionCallbackInfo<Value>& args) {
1387-
// Argument 1: source code
1388-
CHECK(args[0]->IsString());
1389-
Local<String> code = args[0].As<String>();
1387+
Environment* env = Environment::GetCurrent(args);
1388+
Isolate* isolate = env->isolate();
1389+
Local<Context> context = env->context();
13901390

1391-
// Argument 2: filename
1392-
Local<String> filename = String::Empty(args.GetIsolate());
1391+
if (args.Length() == 0) {
1392+
return THROW_ERR_MISSING_ARGS(
1393+
env, "containsModuleSyntax needs at least 1 argument");
1394+
}
1395+
1396+
// Argument 2: filename; if undefined, use empty string
1397+
Local<String> filename = String::Empty(isolate);
13931398
if (!args[1]->IsUndefined()) {
13941399
CHECK(args[1]->IsString());
13951400
filename = args[1].As<String>();
13961401
}
13971402

1398-
Environment* env = Environment::GetCurrent(args);
1399-
Isolate* isolate = env->isolate();
1400-
Local<Context> context = env->context();
1403+
// Argument 1: source code; if undefined, read from filename in argument 2
1404+
Local<String> code;
1405+
if (args[0]->IsUndefined()) {
1406+
CHECK(!filename.IsEmpty());
1407+
const char* filename_str = Utf8Value(isolate, filename).out();
1408+
std::string contents;
1409+
int result = ReadFileSync(&contents, filename_str);
1410+
if (result != 0) {
1411+
isolate->ThrowException(
1412+
ERR_MODULE_NOT_FOUND(isolate, "Cannot read file %s", filename_str));
1413+
return;
1414+
}
1415+
code = String::NewFromUtf8(isolate,
1416+
contents.c_str(),
1417+
v8::NewStringType::kNormal,
1418+
contents.length())
1419+
.ToLocalChecked();
1420+
} else {
1421+
CHECK(args[0]->IsString());
1422+
code = args[0].As<String>();
1423+
}
14011424

14021425
// TODO(geoffreybooth): Centralize this rather than matching the logic in
14031426
// cjs/loader.js and translators.js

0 commit comments

Comments
 (0)