Skip to content

Commit 05ed646

Browse files
committed
src: improve package.json reader performance
1 parent e66cc1c commit 05ed646

File tree

7 files changed

+144
-166
lines changed

7 files changed

+144
-166
lines changed

lib/internal/modules/cjs/loader.js

Lines changed: 2 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,6 @@ const {
8282
pendingDeprecate,
8383
emitExperimentalWarning,
8484
kEmptyObject,
85-
filterOwnProperties,
8685
setOwnProperty,
8786
getLazy,
8887
} = require('internal/util');
@@ -353,36 +352,10 @@ function initializeCJS() {
353352
// -> a.<ext>
354353
// -> a/index.<ext>
355354

356-
const packageJsonCache = new SafeMap();
357-
358355
function readPackage(requestPath) {
359356
const jsonPath = path.resolve(requestPath, 'package.json');
360-
361-
const existing = packageJsonCache.get(jsonPath);
362-
if (existing !== undefined) return existing;
363-
364-
const result = packageJsonReader.read(jsonPath);
365-
const json = result.containsKeys === false ? '{}' : result.string;
366-
if (json === undefined) {
367-
packageJsonCache.set(jsonPath, false);
368-
return false;
369-
}
370-
371-
try {
372-
const filtered = filterOwnProperties(JSONParse(json), [
373-
'name',
374-
'main',
375-
'exports',
376-
'imports',
377-
'type',
378-
]);
379-
packageJsonCache.set(jsonPath, filtered);
380-
return filtered;
381-
} catch (e) {
382-
e.path = jsonPath;
383-
e.message = 'Error parsing ' + jsonPath + ': ' + e.message;
384-
throw e;
385-
}
357+
// Return undefined or the filtered package.json as a JS object
358+
return packageJsonReader.read(jsonPath);
386359
}
387360

388361
let _readPackage = readPackage;

lib/internal/modules/esm/package_config.js

Lines changed: 12 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,10 @@
11
'use strict';
22

33
const {
4-
JSONParse,
5-
ObjectPrototypeHasOwnProperty,
64
SafeMap,
75
StringPrototypeEndsWith,
86
} = primordials;
97
const { URL, fileURLToPath } = require('internal/url');
10-
const {
11-
ERR_INVALID_PACKAGE_CONFIG,
12-
} = require('internal/errors').codes;
13-
14-
const { filterOwnProperties } = require('internal/util');
15-
168

179
/**
1810
* @typedef {string | string[] | Record<string, unknown>} Exports
@@ -42,9 +34,10 @@ function getPackageConfig(path, specifier, base) {
4234
return existing;
4335
}
4436
const packageJsonReader = require('internal/modules/package_json_reader');
45-
const source = packageJsonReader.read(path).string;
46-
if (source === undefined) {
47-
const packageConfig = {
37+
const packageJSON = packageJsonReader.read(path);
38+
39+
if (packageJSON === undefined) {
40+
const json = {
4841
pjsonPath: path,
4942
exists: false,
5043
main: undefined,
@@ -53,48 +46,19 @@ function getPackageConfig(path, specifier, base) {
5346
exports: undefined,
5447
imports: undefined,
5548
};
56-
packageJSONCache.set(path, packageConfig);
57-
return packageConfig;
58-
}
59-
60-
let packageJSON;
61-
try {
62-
packageJSON = JSONParse(source);
63-
} catch (error) {
64-
throw new ERR_INVALID_PACKAGE_CONFIG(
65-
path,
66-
(base ? `"${specifier}" from ` : '') + fileURLToPath(base || specifier),
67-
error.message,
68-
);
49+
packageJSONCache.set(path, json);
50+
return json;
6951
}
7052

71-
let { imports, main, name, type } = filterOwnProperties(packageJSON, ['imports', 'main', 'name', 'type']);
72-
const exports = ObjectPrototypeHasOwnProperty(packageJSON, 'exports') ? packageJSON.exports : undefined;
73-
if (typeof imports !== 'object' || imports === null) {
74-
imports = undefined;
75-
}
76-
if (typeof main !== 'string') {
77-
main = undefined;
78-
}
79-
if (typeof name !== 'string') {
80-
name = undefined;
81-
}
8253
// Ignore unknown types for forwards compatibility
83-
if (type !== 'module' && type !== 'commonjs') {
84-
type = 'none';
54+
if (packageJSON.type !== 'module' && packageJSON.type !== 'commonjs') {
55+
packageJSON.type = 'none';
8556
}
8657

87-
const packageConfig = {
88-
pjsonPath: path,
89-
exists: true,
90-
main,
91-
name,
92-
type,
93-
exports,
94-
imports,
95-
};
96-
packageJSONCache.set(path, packageConfig);
97-
return packageConfig;
58+
packageJSON.pjsonPath = path;
59+
packageJSON.exists = true;
60+
packageJSONCache.set(path, packageJSON);
61+
return packageJSON;
9862
}
9963

10064

lib/internal/modules/package_json_reader.js

Lines changed: 33 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,10 @@
11
'use strict';
22

3-
const { SafeMap } = primordials;
3+
const {
4+
JSONParse,
5+
JSONStringify,
6+
SafeMap,
7+
} = primordials;
48
const { internalModuleReadJSON } = internalBinding('fs');
59
const { pathToFileURL } = require('url');
610
const { toNamespacedPath } = require('path');
@@ -10,30 +14,53 @@ const cache = new SafeMap();
1014
let manifest;
1115

1216
/**
13-
*
17+
* Returns undefined for all failure cases.
1418
* @param {string} jsonPath
1519
*/
1620
function read(jsonPath) {
1721
if (cache.has(jsonPath)) {
1822
return cache.get(jsonPath);
1923
}
2024

21-
const { 0: string, 1: containsKeys } = internalModuleReadJSON(
25+
const {
26+
0: includes_keys,
27+
1: name,
28+
2: main,
29+
3: exports,
30+
4: imports,
31+
5: type,
32+
} = internalModuleReadJSON(
2233
toNamespacedPath(jsonPath),
2334
);
24-
const result = { string, containsKeys };
35+
36+
let result;
37+
38+
if (includes_keys !== undefined) {
39+
result = { name, main, exports, imports, type, includes_keys };
40+
41+
// Execute JSONParse on demand for improving performance
42+
if (exports) {
43+
result.exports = JSONParse(exports);
44+
}
45+
46+
if (imports) {
47+
result.imports = JSONParse(imports);
48+
}
49+
}
50+
2551
const { getOptionValue } = require('internal/options');
26-
if (string !== undefined) {
52+
if (name !== undefined) {
2753
if (manifest === undefined) {
2854
manifest = getOptionValue('--experimental-policy') ?
2955
require('internal/process/policy').manifest :
3056
null;
3157
}
3258
if (manifest !== null) {
3359
const jsonURL = pathToFileURL(jsonPath);
34-
manifest.assertIntegrity(jsonURL, string);
60+
manifest.assertIntegrity(jsonURL, JSONStringify(result));
3561
}
3662
}
63+
3764
cache.set(jsonPath, result);
3865
return result;
3966
}

src/node_file.cc

Lines changed: 67 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -32,8 +32,10 @@
3232
#include "tracing/trace_event.h"
3333

3434
#include "req_wrap-inl.h"
35+
#include "simdjson.h"
3536
#include "stream_base-inl.h"
3637
#include "string_bytes.h"
38+
#include "v8-primitive.h"
3739

3840
#include <fcntl.h>
3941
#include <sys/types.h>
@@ -1079,41 +1081,77 @@ static void InternalModuleReadJSON(const FunctionCallbackInfo<Value>& args) {
10791081
}
10801082

10811083
const size_t size = offset - start;
1082-
char* p = &chars[start];
1083-
char* pe = &chars[size];
1084-
char* pos[2];
1085-
char** ppos = &pos[0];
1086-
1087-
while (p < pe) {
1088-
char c = *p++;
1089-
if (c == '\\' && p < pe && *p == '"') p++;
1090-
if (c != '"') continue;
1091-
*ppos++ = p;
1092-
if (ppos < &pos[2]) continue;
1093-
ppos = &pos[0];
1094-
1095-
char* s = &pos[0][0];
1096-
char* se = &pos[1][-1]; // Exclude quote.
1097-
size_t n = se - s;
1098-
1099-
if (n == 4) {
1100-
if (0 == memcmp(s, "main", 4)) break;
1101-
if (0 == memcmp(s, "name", 4)) break;
1102-
if (0 == memcmp(s, "type", 4)) break;
1103-
} else if (n == 7) {
1104-
if (0 == memcmp(s, "exports", 7)) break;
1105-
if (0 == memcmp(s, "imports", 7)) break;
1084+
simdjson::ondemand::parser parser;
1085+
simdjson::padded_string json_string(chars.data() + start, size);
1086+
simdjson::ondemand::document document;
1087+
simdjson::ondemand::object obj;
1088+
auto error = parser.iterate(json_string).get(document);
1089+
1090+
if (error || document.get_object().get(obj)) {
1091+
args.GetReturnValue().Set(Array::New(isolate));
1092+
return;
1093+
}
1094+
1095+
auto js_string = [&](std::string_view sv) {
1096+
return ToV8Value(env->context(), sv, isolate).ToLocalChecked();
1097+
};
1098+
1099+
bool includes_keys{false};
1100+
Local<Value> name = Undefined(isolate);
1101+
Local<Value> main = Undefined(isolate);
1102+
Local<Value> exports = Undefined(isolate);
1103+
Local<Value> imports = Undefined(isolate);
1104+
Local<Value> type = Undefined(isolate);
1105+
1106+
// Check for "name" field
1107+
std::string_view name_value{};
1108+
if (!obj["name"].get_string().get(name_value)) {
1109+
name = js_string(name_value);
1110+
includes_keys = true;
1111+
}
1112+
1113+
// Check for "main" field
1114+
std::string_view main_value{};
1115+
if (!obj["main"].get_string().get(main_value)) {
1116+
main = js_string(main_value);
1117+
includes_keys = true;
1118+
}
1119+
1120+
simdjson::ondemand::object subobject;
1121+
std::string_view subobject_value{};
1122+
1123+
// Check for "exports" field
1124+
if (!obj["exports"].get_object().get(subobject)) {
1125+
if (!subobject.raw_json().get(subobject_value)) {
1126+
exports = js_string(subobject_value);
1127+
includes_keys = true;
11061128
}
11071129
}
11081130

1131+
// Check for "imports" field
1132+
if (!obj["imports"].get_object().get(subobject)) {
1133+
if (!subobject.raw_json().get(subobject_value)) {
1134+
imports = js_string(subobject_value);
1135+
includes_keys = true;
1136+
}
1137+
}
1138+
1139+
// Check for "type" field
1140+
std::string_view type_value{};
1141+
if (!obj["type"].get(type_value)) {
1142+
type = js_string(type_value);
1143+
includes_keys = true;
1144+
}
11091145

11101146
Local<Value> return_value[] = {
1111-
String::NewFromUtf8(isolate,
1112-
&chars[start],
1113-
v8::NewStringType::kNormal,
1114-
size).ToLocalChecked(),
1115-
Boolean::New(isolate, p < pe ? true : false)
1147+
Boolean::New(isolate, includes_keys),
1148+
name,
1149+
main,
1150+
exports,
1151+
imports,
1152+
type,
11161153
};
1154+
11171155
args.GetReturnValue().Set(
11181156
Array::New(isolate, return_value, arraysize(return_value)));
11191157
}

test/es-module/test-esm-invalid-pjson.js

Lines changed: 0 additions & 29 deletions
This file was deleted.

test/fixtures/errors/force_colors.snapshot

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,10 @@ throw new Error('Should include grayed stack trace')
44

55
Error: Should include grayed stack trace
66
at Object.<anonymous> (/test*force_colors.js:1:7)
7-
 at Module._compile (node:internal*modules*cjs*loader:1255:14)
8-
 at Module._extensions..js (node:internal*modules*cjs*loader:1309:10)
9-
 at Module.load (node:internal*modules*cjs*loader:1113:32)
10-
 at Module._load (node:internal*modules*cjs*loader:960:12)
7+
 at Module._compile (node:internal*modules*cjs*loader:1228:14)
8+
 at Module._extensions..js (node:internal*modules*cjs*loader:1282:10)
9+
 at Module.load (node:internal*modules*cjs*loader:1086:32)
10+
 at Module._load (node:internal*modules*cjs*loader:933:12)
1111
 at Function.executeUserEntryPoint [as runMain] (node:internal*modules*run_main:83:12)
1212
 at node:internal*main*run_main_module:23:47
1313

0 commit comments

Comments
 (0)