Skip to content

Commit dd7fbf9

Browse files
author
Robert Jackson
authored
Merge pull request #242 from davecombs/fix_file_io
Remove extraneous file I/O when checking the same package version
2 parents 1f8d646 + e17f244 commit dd7fbf9

1 file changed

Lines changed: 21 additions & 13 deletions

File tree

src/dependency-version-checker.js

Lines changed: 21 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,20 @@
11
'use strict';
2-
const fs = require('fs');
32
const semver = require('semver');
43
const getProject = require('./get-project');
5-
const resolvePackage = require('resolve-package-path');
4+
const resolvePackagePath = require('resolve-package-path');
65

6+
/*
7+
* Retrieve the version field from the package.json file contents.
8+
* NOTE: the callers have already checked that the filePath is not null/undefined.
9+
*/
710
function getVersionFromJSONFile(filePath) {
8-
if (fs.existsSync(filePath)) {
9-
let content = fs.readFileSync(filePath);
10-
11-
try {
12-
return JSON.parse(content).version;
13-
} catch (exception) {
14-
return null;
15-
}
11+
try {
12+
// Use the require cache to avoid file I/O after first call on a given path.
13+
let pkg = require(filePath);
14+
return pkg.version || null;
15+
} catch (err) {
16+
// file doesn't exist or is not a file or is not parseable.
17+
return null;
1618
}
1719
}
1820

@@ -23,12 +25,18 @@ class DependencyVersionChecker {
2325
constructor(parent, name) {
2426
this._parent = parent;
2527
this.name = name;
26-
let addon = this._parent._addon;
27-
let basedir = addon.root || getProject(addon).root;
28-
this._jsonPath = resolvePackage(this.name, basedir);
2928
}
3029

3130
get version() {
31+
if (this._jsonPath === undefined) {
32+
// get the path to the package.json file. resolvePackagePath will
33+
// return the path or null, never undefined, so we can use that
34+
// to only resolvePackagePath once.
35+
let addon = this._parent._addon;
36+
let basedir = addon.root || getProject(addon).root;
37+
this._jsonPath = resolvePackagePath(this.name, basedir);
38+
}
39+
3240
if (this._version === undefined && this._jsonPath) {
3341
this._version = getVersionFromJSONFile(this._jsonPath);
3442
}

0 commit comments

Comments
 (0)