RxJS 5 operator to write data into a CSV file
Work in both JavaScript and TypeScript
npm install rx-to-csv
Import this library and it will add toCSV
operator to the rxjs Observable
class.
public toCSV(path: string, columns: Array<string>, options?: any): Observable
This operator will search values in its input by column names and write them into the target CSV file via a write file stream.
Parameters:
- path: csv file path
- columns: an array of column names
- options: optional configuration for the csv creation
- wrapText: a boolean value indicating whether to wrap text values with
"
. Default:true
- delimiter: a character to separate values. Default:
,
- wrapText: a boolean value indicating whether to wrap text values with
Generate a CSV file from data flow:
import { Observable } from 'rxjs';
import 'rx-to-csv';
let data = [
{ id: 1, name: 'Mike' },
{ id: 2, name: 'Tommy' }
];
Observable.of(...data)
.toCSV('data.csv', ['id', 'name'])
.subscribe();
Download data from a PostgreSQL dadtabase and save it as a CSV file:
import pgrx from 'pg-reactive';
import 'rx-to-csv';
let db = new pgrx('connection string');
db.query('SELECT id, display_name FROM users')
.map((row) => {
// convert the data to match column names
return {
id: row.id,
name: row.display_name
};
})
.toCSV('data.csv', ['id', 'name'])
.subscribe();
MIT