From 2e26f472eab3a3d235f3e625e4d82716f0e4dd9a Mon Sep 17 00:00:00 2001 From: Jiiks Date: Tue, 16 Jan 2018 03:49:26 +0200 Subject: [PATCH] FileUtils --- client/src/modules/index.js | 2 +- client/src/modules/utils.js | 88 ++++++++++++++++++++++++++++++++++++- 2 files changed, 88 insertions(+), 2 deletions(-) diff --git a/client/src/modules/index.js b/client/src/modules/index.js index 0240d6cf..783f9629 100644 --- a/client/src/modules/index.js +++ b/client/src/modules/index.js @@ -1,4 +1,4 @@ -export { Logger, Utils } from './utils'; +export { Logger, Utils, FileUtils } from './utils'; export { PluginManager } from './pluginmanager'; export { Pluging } from './plugin'; export { BDIpc } from './bdipc'; diff --git a/client/src/modules/utils.js b/client/src/modules/utils.js index 1d969556..5238edac 100644 --- a/client/src/modules/utils.js +++ b/client/src/modules/utils.js @@ -48,7 +48,93 @@ class Utils { cb(...args); } } + + static async tryParseJson(jsonString) { + try { + return JSON.parse(jsonString); + } catch (err) { + throw ({ + 'message': 'Failed to parse json', + err + }); + } + } } -module.exports = { Logger, Utils } \ No newline at end of file +class FileUtils { + + static async fileExists(path) { + return new Promise((resolve, reject) => { + fs.stat(path, (err, stats) => { + if (err) return reject({ + 'message': `No such file or directory: ${err.path}`, + err + }); + + if (!stats.isFile()) return reject({ + 'message': `Not a file: ${path}`, + stats + }); + + resolve(); + }); + }); + } + + static async directoryExists(path) { + return new Promise(resolve => { + fs.stat(path, (err, stats) => { + if (err) return reject({ + 'message': `Directory does not exist: ${path}`, + err + }); + + if (!stats.isDirectory()) return reject({ + 'message': `Not a directory: ${path}`, + stats + }); + + resolve(); + }); + }); + } + + static async readFile(path) { + try { + await this.fileExists(path); + } catch (err) { + throw (err); + } + + return new Promise(resolve => { + fs.readFile(path, 'utf-8', (err, data) => { + if (err) reject({ + 'message': `Could not read file: ${path}`, + err + }); + + resolve(data); + }); + }); + } + + static async readJsonFromFile(path) { + let readFile; + try { + readFile = await this.readFile(path); + } catch (err) { + throw (err); + } + + try { + const parsed = await Utils.tryParseJson(readFile); + return parsed; + } catch (err) { + throw (Object.assign(err, { path })); + } + } +} + + +module.exports = { Logger, Utils, FileUtils } \ No newline at end of file