0
Fork 0
mirror of https://github.com/verdaccio/verdaccio.git synced 2024-12-30 22:34:10 -05:00

fix: 🐛 check error code to prevent data loss

This commit is contained in:
Meeeeow 2017-08-19 00:34:00 +08:00 committed by Juan Picado @jotadeveloper
parent a91a0d3bef
commit 93aae05e63
No known key found for this signature in database
GPG key ID: 18AC54485952D158

View file

@ -2,6 +2,7 @@
const fs = require('fs'); const fs = require('fs');
const Path = require('path'); const Path = require('path');
const logger = require('../../logger');
/** /**
* Handle local database. * Handle local database.
@ -15,10 +16,28 @@ const Path = require('path');
*/ */
constructor(path) { constructor(path) {
this.path = path; this.path = path;
let dbFile;
try { try {
this.data = JSON.parse(fs.readFileSync(this.path, 'utf8')); dbFile = fs.readFileSync(this.path, 'utf8');
} catch(_) { } catch (err) {
this.data = {list: []}; if (err.code === 'ENOENT') { // Only recreate if file not found to prevent data loss
this.data = {list: []};
} else {
logger.logger.error(
'Failed to read package database file, please check the error printed below and fix it manually:\n',
`File Path: ${this.path}\n\n`,
err
);
throw new Error('Package database file unreachable');
}
}
try {
this.data = JSON.parse(dbFile);
} catch(err) {
logger.logger.error(err);
throw new Error(`Package database file corrupted (invalid JSON), please fix it manually.\nFile Path: ${this.path}`);
} }
} }