Closed simoneb closed 6 months ago
Formatting an Array
as CSV is rather common. I'm not sure this functionality belongs within the package as it's easy enough to roll your own. But if it did, it might look something like this:
const Table = require('cli-table3');
const rowToCSV = (row, opts = {}) => {
const { encapsulator = '', delimeter = ',' } = opts;
return row.map((v) => {
const { content = v } = v;
return [encapsulator, content, encapsulator].join('');
}).join(delimeter);
};
Table.prototype.toCSV = function (opts = {}) {
const { lineSeparator = '\n' } = opts;
const lines = [];
if (this.head && this.head.length) {
lines.push(rowToCSV(this.head, opts));
}
this.forEach((row) => lines.push(rowToCSV(row, opts)));
return lines.join(lineSeparator);
};
const myTable = new Table({ head: ['col1', 'col2', 'col3'] });
myTable.push(['1-1', '1-2', '1-3']);
myTable.push(['2-1', '2-2', '2-3']);
myTable.push(['3-1', '3-2', '3-3']);
myTable.push(['4-1', '4-2', '4-3']);
myTable.push(['5-1', '5-2', '5-3']);
console.log(myTable.toCSV());
console.log(myTable.toCSV({ encapsulator: '"', delimeter: ':', lineSeparator: '\n\r' }));
myTable.toCSV()
returns:
col1,col2,col3
1-1,1-2,1-3
2-1,2-2,2-3
3-1,3-2,3-3
4-1,4-2,4-3
5-1,5-2,5-3
AND
myTable.toCSV({ encapsulator: '"', delimeter: ':', lineSeparator: '\n\r' });
returns:
"col1":"col2":"col3"
"1-1":"1-2":"1-3"
"2-1":"2-2":"2-3"
"3-1":"3-2":"3-3"
"4-1":"4-2":"4-3"
"5-1":"5-2":"5-3"
Going to close this request unless there is more interest as it's pretty easy to convert a table array to CSV as is. Thanks for posting!
Thanks :)
Thanks for this project, it's really great work.
I'm building a CLI that could benefit from both displaying data on the terminal to be consumed by a human, and generating machine readable output, for example in CSV format.
Although I'm not very familiar with the codebase, I assume that once you have the data structure in memory, generating a CSV string would most likely be simpler than generating a ASCII table.
Have you considered adding this feature before? It would be really cool to have a method such as
.toCSV()
which produces a CSV representation of the table.