Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save brandonhimpfen/80f3d25d165e7826fe63607a6a8b1220 to your computer and use it in GitHub Desktop.

Select an option

Save brandonhimpfen/80f3d25d165e7826fe63607a6a8b1220 to your computer and use it in GitHub Desktop.
Convert CSV to JSONL in Node.js with selected columns, safe CSV parsing, basic type coercion, and streaming output (no deps).
#!/usr/bin/env node
/**
* Convert CSV to JSONL with selected columns and type coercion.
*
* Usage:
* node node-csv-to-jsonl-selected-columns.js input.csv --columns=id,name,active,score > output.jsonl
* node node-csv-to-jsonl-selected-columns.js input.csv --columns=id,name --types=id:number,active:boolean
*/
const fs = require("fs");
const readline = require("readline");
const { once } = require("events");
function parseArgs(argv) {
const args = { file: null, columns: null, types: {}, delimiter: "," };
for (const arg of argv.slice(2)) {
if (!args.file && !arg.startsWith("--")) args.file = arg;
else if (arg.startsWith("--columns=")) args.columns = arg.slice(10).split(",").map(s => s.trim()).filter(Boolean);
else if (arg.startsWith("--types=")) {
for (const pair of arg.slice(8).split(",")) {
const [key, type] = pair.split(":");
if (key && type) args.types[key.trim()] = type.trim();
}
} else if (arg.startsWith("--delimiter=")) args.delimiter = arg.slice(12);
else if (arg === "-h" || arg === "--help") args.help = true;
else throw new Error(`Unknown argument: ${arg}`);
}
return args;
}
function usage() {
console.error(`Usage: node node-csv-to-jsonl-selected-columns.js <input.csv> --columns=<col1,col2,...> [--types=col:type,...]
Types:
string, number, boolean, date
Examples:
node node-csv-to-jsonl-selected-columns.js users.csv --columns=id,name,email > users.jsonl
node node-csv-to-jsonl-selected-columns.js users.csv --columns=id,name,active --types=id:number,active:boolean > users.jsonl
`);
}
function parseCSVLine(line, delimiter = ",") {
const out = [];
let cur = "";
let inQuotes = false;
for (let i = 0; i < line.length; i++) {
const ch = line[i];
if (inQuotes) {
if (ch === '"') {
if (line[i + 1] === '"') {
cur += '"';
i++;
} else {
inQuotes = false;
}
} else {
cur += ch;
}
continue;
}
if (ch === '"') {
inQuotes = true;
} else if (ch === delimiter) {
out.push(cur);
cur = "";
} else {
cur += ch;
}
}
out.push(cur);
return out;
}
function coerce(value, type) {
if (value === "") return null;
switch (type) {
case "number": {
const n = Number(value);
return Number.isFinite(n) ? n : null;
}
case "boolean":
return /^(true|1|yes|y)$/i.test(value)
? true
: /^(false|0|no|n)$/i.test(value)
? false
: null;
case "date": {
const d = new Date(value);
return Number.isNaN(d.getTime()) ? null : d.toISOString();
}
case "string":
default:
return value;
}
}
async function writeLine(line) {
if (!process.stdout.write(line + "\n")) {
await once(process.stdout, "drain");
}
}
async function main() {
const args = parseArgs(process.argv);
if (args.help || !args.file || !args.columns || args.columns.length === 0) {
usage();
process.exit(args.help ? 0 : 2);
}
const rl = readline.createInterface({
input: fs.createReadStream(args.file, { encoding: "utf8" }),
crlfDelay: Infinity,
});
let headers = null;
let lineNum = 0;
let rows = 0;
for await (const line of rl) {
lineNum++;
if (!line.trim()) continue;
const fields = parseCSVLine(line, args.delimiter);
if (lineNum === 1) {
headers = fields;
continue;
}
const record = {};
for (const col of args.columns) {
const index = headers.indexOf(col);
if (index === -1) {
throw new Error(`Column not found: ${col}`);
}
const raw = fields[index] ?? "";
record[col] = coerce(raw, args.types[col] || "string");
}
await writeLine(JSON.stringify(record));
rows++;
}
console.error(`Done. Wrote ${rows} JSONL row(s).`);
}
main().catch((err) => {
console.error("ERROR:", err && err.stack ? err.stack : err);
process.exit(1);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment