aboutsummaryrefslogtreecommitdiff
path: root/src/lib/export.ts
diff options
context:
space:
mode:
authorBobby <[email protected]>2022-01-28 16:54:18 -0500
committerBobby <[email protected]>2022-01-28 16:54:18 -0500
commit5aeab5e6a0e71c6a3e8ddfb02c481dac731148de (patch)
tree365aba209616d46d33f73b6e4c9743d2e16e54b1 /src/lib/export.ts
parentfae750e3027a6377e9de8dafe278efce4d262df4 (diff)
downloadizuku.js-5aeab5e6a0e71c6a3e8ddfb02c481dac731148de.tar.xz
izuku.js-5aeab5e6a0e71c6a3e8ddfb02c481dac731148de.zip
feat: function to save to CSV
Diffstat (limited to 'src/lib/export.ts')
-rw-r--r--src/lib/export.ts42
1 files changed, 42 insertions, 0 deletions
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'
+ }.`
+ );
+}