From 9ed91b01f89084b83bd2df8a93fdc14f0b36bc24 Mon Sep 17 00:00:00 2001 From: Dave Combs Date: Mon, 1 Feb 2021 14:58:19 -0800 Subject: [PATCH] backport fix to getVersionFromJSONFile to avoid unnecessary I/O --- src/dependency-version-checker.js | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/src/dependency-version-checker.js b/src/dependency-version-checker.js index 9ac5682..b0fe461 100644 --- a/src/dependency-version-checker.js +++ b/src/dependency-version-checker.js @@ -1,17 +1,19 @@ 'use strict'; -const fs = require('fs'); const semver = require('semver'); +/* + * Retrieve the version field from the package.json file contents. + * NOTE: the callers have already checked that the filePath is not null/undefined. + */ function getVersionFromJSONFile(filePath) { - if (fs.existsSync(filePath)) { - let content = fs.readFileSync(filePath); - - try { - return JSON.parse(content).version; - } catch (exception) { - return null; - } + try { + // Use the require cache to avoid file I/O after first call on a given path. + let pkg = require(filePath); + return pkg.version; + } catch (err) { + // file doesn't exist or is not a file or is not parseable. + return null; } } @@ -51,11 +53,9 @@ class DependencyVersionChecker { let message = _message; if (!message) { - message = `The addon \`${this._parent._addon.name}\` requires the ${ - this._type - } package \`${this.name}\` to be above ${compareVersion}, but you have ${ - this.version - }.`; + message = `The addon \`${this._parent._addon.name}\` requires the ${this + ._type} package \`${this + .name}\` to be above ${compareVersion}, but you have ${this.version}.`; } if (!this.isAbove(compareVersion)) {