From fa1e98ce4df8e91414bc1875898c62c69552d6a9 Mon Sep 17 00:00:00 2001 From: sundowndev Date: Wed, 27 Feb 2019 17:02:17 +0100 Subject: [PATCH] Export command --- commands/export/index.js | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 commands/export/index.js diff --git a/commands/export/index.js b/commands/export/index.js new file mode 100644 index 0000000..9901a88 --- /dev/null +++ b/commands/export/index.js @@ -0,0 +1,39 @@ +const fs = require('fs'); + +export const command = 'export '; +export const description = 'Export data to json or csv'; + +export const action = async ({ args, jsonToCsv, logger }) => { + const [type] = args._ + const dataDir = global.rootPath + "/data"; + + // if data directory doesn't exists, create it + if (!fs.existsSync(dataDir)) { + fs.mkdirSync(dataDir); + } + + switch (type) { + case 'json': + fs.writeFile(dataDir + "/db.json", JSON.stringify(global.data), function (err) { + if (err) { + return logger.error(err); + } + }); + + logger.info('Successfully exported data.'); + break; + case 'csv': + const csv = await jsonToCsv.parse(global.data.students); + + fs.writeFile(dataDir + "/students.csv", csv, function (err) { + if (err) { + return logger.error(err); + } + }); + + logger.info('Successfully exported data.'); + break; + default: + logger.error('You need to specify a valid type (json or csv).'); + } +};