aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/index.ts3
-rw-r--r--src/lib/export.ts42
2 files changed, 44 insertions, 1 deletions
diff --git a/src/index.ts b/src/index.ts
index 8214328..d076567 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -9,7 +9,7 @@ import {
import { show, head, tail } from './lib/display';
import { getSize, info } from './lib/info';
import { flatten, fromJSON, fromCSV, searchValue } from './lib/data';
-import { toJSON } from './lib/export';
+import { toJSON, toCSV } from './lib/export';
import { isArrayOfType, range, flattenJSON } from './helpers/arrayFunctions';
class Izuku {
@@ -83,6 +83,7 @@ class Izuku {
};
public title = title;
public toJSON = toJSON;
+ public toCSV = toCSV;
}
class Frame extends Izuku {
diff --git a/src/lib/export.ts b/src/lib/export.ts
index 137e534..652f2e9 100644
--- a/src/lib/export.ts
+++ b/src/lib/export.ts
@@ -42,3 +42,45 @@ export function toJSON(this: Frame, path?: string, filename?: string): void {
}.`
);
}
+
+/**
+ * toCSV - converts frame to CSV file, takes a path to save the file. Path is optional. If no path is provided, the file is saved in the current directory
+ * @param frame: the frame to be converted
+ * @param path: @optional the path to save the file
+ * @param filename: @optional the name of the file
+ */
+export function toCSV(this: Frame, path?: string, filename?: string): void {
+ const data = this.rowdata;
+ const header = this.columns;
+
+ // create a csv string, with keys as the header and values as the row data
+ const csv = data.map((row: any[]) => {
+ const csvRow = header.map((col: string) => {
+ if (row[header.indexOf(col)]) {
+ return row[header.indexOf(col)];
+ }
+ return '';
+ });
+ return csvRow.join(',');
+ });
+
+ // add the header to the csv string
+ csv.unshift(header.join(','));
+
+ // save the csv string to a file
+ if (path) {
+ writeFileSync(
+ `${path}/${filename ? `${filename}` : 'data'}.csv`,
+ csv.join('\n')
+ );
+ } else {
+ writeFileSync(`${filename ? `${filename}` : 'data'}.csv`, csv.join('\n'));
+ }
+
+ // console.log the file path
+ console.log(
+ `${filename ? `${filename}` : 'data'}.csv saved at ${
+ path ? path : 'root level'
+ }.`
+ );
+}