From 93aae05e6381ced7ba52f7512de326f029ff3abe Mon Sep 17 00:00:00 2001 From: Meeeeow Date: Sat, 19 Aug 2017 00:34:00 +0800 Subject: [PATCH] fix: :bug: check error code to prevent data loss --- src/lib/storage/local/local-data.js | 25 ++++++++++++++++++++++--- 1 file changed, 22 insertions(+), 3 deletions(-) diff --git a/src/lib/storage/local/local-data.js b/src/lib/storage/local/local-data.js index 658c5b017..5c46ea081 100644 --- a/src/lib/storage/local/local-data.js +++ b/src/lib/storage/local/local-data.js @@ -2,6 +2,7 @@ const fs = require('fs'); const Path = require('path'); +const logger = require('../../logger'); /** * Handle local database. @@ -15,10 +16,28 @@ const Path = require('path'); */ constructor(path) { this.path = path; + let dbFile; + try { - this.data = JSON.parse(fs.readFileSync(this.path, 'utf8')); - } catch(_) { - this.data = {list: []}; + dbFile = fs.readFileSync(this.path, 'utf8'); + } catch (err) { + 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}`); } }