From fdbb6dd042a560fc5d3b3ad682a13ddf506128e6 Mon Sep 17 00:00:00 2001 From: Ben Noordhuis Date: Thu, 9 Nov 2017 13:26:46 +0100 Subject: [PATCH] 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 Reviewed-By: Colin Ihrig Reviewed-By: James M Snell --- lib/module.js | 3 +++ test/fixtures/packages/invalid/index.js | 1 - test/fixtures/packages/invalid/package.json | 1 - test/sequential/test-module-loading.js | 8 -------- 4 files changed, 3 insertions(+), 10 deletions(-) delete mode 100644 test/fixtures/packages/invalid/index.js delete mode 100644 test/fixtures/packages/invalid/package.json diff --git a/lib/module.js b/lib/module.js index e418a1a3e08440..b9de9c3edfb782 100644 --- a/lib/module.js +++ b/lib/module.js @@ -120,6 +120,9 @@ function readPackage(requestPath) { return false; } + if (!/"main"/.test(json)) + return packageMainCache[requestPath] = undefined; + try { var pkg = packageMainCache[requestPath] = JSON.parse(json).main; } catch (e) { diff --git a/test/fixtures/packages/invalid/index.js b/test/fixtures/packages/invalid/index.js deleted file mode 100644 index 014fa39dc365d1..00000000000000 --- a/test/fixtures/packages/invalid/index.js +++ /dev/null @@ -1 +0,0 @@ -exports.ok = 'ok'; diff --git a/test/fixtures/packages/invalid/package.json b/test/fixtures/packages/invalid/package.json deleted file mode 100644 index 004e1e20324524..00000000000000 --- a/test/fixtures/packages/invalid/package.json +++ /dev/null @@ -1 +0,0 @@ -{,} diff --git a/test/sequential/test-module-loading.js b/test/sequential/test-module-loading.js index 47916d352d729a..790331a37b9d80 100644 --- a/test/sequential/test-module-loading.js +++ b/test/sequential/test-module-loading.js @@ -100,14 +100,6 @@ const d2 = require('../fixtures/b/d'); 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', 'Failed loading package'); assert.strictEqual(require('../fixtures/packages/main').ok, 'ok',