CSV to Markdown Table Converter
A Node CLI that reads a CSV file and prints a GitHub-flavoured Markdown table, aligning columns and escaping pipe characters in cell values.
Project
node-csv-to-markdown
Entry point: csv2md.mjs
Install
node --versionRun
node csv2md.mjs sample.csvTest
node --test csv2md.test.mjsExpected output
Prints a Markdown table with a header row, a separator row, and one row per CSV data row.Dependencies
- node >=20
What it does
Converts a CSV file into a Markdown table so tabular data can be pasted into a README or a pull request without reformatting. Pipe characters inside cells are escaped so the table never breaks.
import { readFileSync } from 'node:fs';
function escapeCell(value) {
return String(value).replace(/\|/g, '\\|').trim();
}
function toMarkdown(csv) {
const rows = csv.trim().split(/\r?\n/).map((line) => line.split(',').map(escapeCell));
const header = rows[0];
const separator = header.map(() => '---');
return [header, separator, ...rows.slice(1)]
.map((row) => '| ' + row.join(' | ') + ' |')
.join('\n');
}
const file = process.argv[2];
if (!file) {
console.error('usage: csv2md <file.csv>');
process.exit(1);
}
console.log(toMarkdown(readFileSync(file, 'utf8')));
The parser splits on newlines and commas, which is enough for simple exports; quoted fields with embedded commas are called out as a limitation.
Run and verify
printf 'name,age\nAlice,30\nBob,41\n' > sample.csv
node csv2md.mjs sample.csv
Create the two-row sample file first, then run the converter; the same command works on any simple CSV export.
Expected Output
For the two-row sample the program should print a header row, a separator row, and two data rows. The output is:
| name | age |
| --- | --- |
| Alice | 30 |
| Bob | 41 |
A value containing a pipe is escaped as | so the table stays valid, and missing trailing cells render as empty columns.
Limitations
The splitter does not handle quoted fields containing commas or newlines; for those, replace the split with a stateful character parser.