diff --git a/lib/tritonapi.js b/lib/tritonapi.js index e31ef74..a68d2d4 100644 --- a/lib/tritonapi.js +++ b/lib/tritonapi.js @@ -145,27 +145,32 @@ TritonApi.prototype._cacheGetJson = function _cacheGetJson(key, cb) { assert.func(cb, 'cb'); var keyPath = path.resolve(this.cacheDir, key); - fs.exists(keyPath, function (exists) { - if (!exists) { - self.log.trace({keyPath: keyPath}, 'cache file does not exist'); + fs.readFile(keyPath, 'utf8', function (err, data) { + if (err && err.code === 'ENOENT') { + self.log.trace({keyPath: keyPath}, + 'cache file does not exist'); + return cb(); + } else if (err) { + self.log.warn({err: err, keyPath: keyPath}, + 'error reading cache file'); return cb(); } - fs.readFile(keyPath, 'utf8', function (err, data) { - if (err) { - self.log.warn({err: err, keyPath: keyPath}, - 'error reading cache file'); - return cb(); - } - var obj; - try { - obj = JSON.parse(data); - } catch (dataErr) { - self.log.warn({err: dataErr, keyPath: keyPath}, - 'error parsing JSON cache file'); - return cb(); - } - cb(null, obj); - }); + var obj; + try { + obj = JSON.parse(data); + } catch (dataErr) { + self.log.trace({err: dataErr, keyPath: keyPath}, + 'error parsing JSON cache file, removing'); + fs.unlink(keyPath, function (err2) { + if (err2) { + self.log.warn({err: err2}, + 'failed to remove JSON cache file'); + } + cb(err2); + }); + return; + } + cb(null, obj); }); }; @@ -252,7 +257,7 @@ TritonApi.prototype.getImage = function getImage(name, cb) { assert.string(name, 'name'); assert.func(cb, 'cb'); - if (common.UUID_RE.test(name)) { + if (common.isUUID(name)) { this.cloudapi.getImage({id: name}, function (err, img) { if (err) { cb(err); @@ -313,7 +318,7 @@ TritonApi.prototype.getPackage = function getPackage(name, cb) { assert.string(name, 'name'); assert.func(cb, 'cb'); - if (common.UUID_RE.test(name)) { + if (common.isUUID(name)) { this.cloudapi.getPackage({id: name}, function (err, pkg) { if (err) { cb(err);