module: speed up package.json parsing

If the package.json does not contain the string '"main"', skip parsing
it to JSON.

Note that this changes the behavior of the module loader in the presence
of package.json files that don't contain legal JSON.  Such files used to
throw an exception but now they are simply ignored unless they contain a
"main" property.

To me, that seems like a good trade-off: I observe a 25% reduction in
start-up time on a medium-sized application[0].

[0] https://github.com/strongloop/sls-sample-app

PR-URL: https://github.com/nodejs/node/pull/15767
Reviewed-By: Anna Henningsen <anna@addaleax.net>
Reviewed-By: Colin Ihrig <cjihrig@gmail.com>
Reviewed-By: James M Snell <jasnell@gmail.com>
This commit is contained in:
Ben Noordhuis 2017-11-09 13:26:46 +01:00
parent 1132ea7434
commit fdbb6dd042
4 changed files with 3 additions and 10 deletions

View File

@ -120,6 +120,9 @@ function readPackage(requestPath) {
return false; return false;
} }
if (!/"main"/.test(json))
return packageMainCache[requestPath] = undefined;
try { try {
var pkg = packageMainCache[requestPath] = JSON.parse(json).main; var pkg = packageMainCache[requestPath] = JSON.parse(json).main;
} catch (e) { } catch (e) {

View File

@ -1 +0,0 @@
exports.ok = 'ok';

View File

@ -1 +0,0 @@
{,}

View File

@ -100,14 +100,6 @@ const d2 = require('../fixtures/b/d');
assert.notStrictEqual(threeFolder, three); assert.notStrictEqual(threeFolder, three);
} }
console.error('test package.json require() loading');
assert.throws(
function() {
require('../fixtures/packages/invalid');
},
/^SyntaxError: Error parsing .+: Unexpected token , in JSON at position 1$/
);
assert.strictEqual(require('../fixtures/packages/index').ok, 'ok', assert.strictEqual(require('../fixtures/packages/index').ok, 'ok',
'Failed loading package'); 'Failed loading package');
assert.strictEqual(require('../fixtures/packages/main').ok, 'ok', assert.strictEqual(require('../fixtures/packages/main').ok, 'ok',