Created
May 31, 2026 17:20
-
-
Save brandonhimpfen/b702e42c23849434923c03fe05ec36fa to your computer and use it in GitHub Desktop.
Convert JSONL/NDJSON to CSV in Node.js with selected columns, nested key paths, safe CSV escaping, and streaming output (no deps).
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env node | |
| /** | |
| * Convert JSONL (NDJSON) to CSV with selected columns. | |
| * | |
| * Features: | |
| * - Reads JSONL from stdin | |
| * - Writes CSV to stdout | |
| * - Supports selected columns | |
| * - Supports nested paths like user.email | |
| * - Safely escapes CSV values | |
| * - Handles stdout backpressure | |
| * - No dependencies | |
| * | |
| * Usage: | |
| * cat input.jsonl | node node-jsonl-to-csv-selected-columns.js --columns=id,name,email > output.csv | |
| * cat input.jsonl | node node-jsonl-to-csv-selected-columns.js --columns=id,user.email,user.country > output.csv | |
| */ | |
| const readline = require("readline"); | |
| const { once } = require("events"); | |
| function usage() { | |
| console.error(`Usage: cat input.jsonl | node node-jsonl-to-csv-selected-columns.js --columns=<col1,col2,...> | |
| Examples: | |
| cat input.jsonl | node node-jsonl-to-csv-selected-columns.js --columns=id,name,email > output.csv | |
| cat input.jsonl | node node-jsonl-to-csv-selected-columns.js --columns=id,user.email,user.country > output.csv | |
| `); | |
| } | |
| function parseArgs(argv) { | |
| const args = { | |
| columns: null, | |
| help: false, | |
| }; | |
| for (const arg of argv.slice(2)) { | |
| if (arg.startsWith("--columns=")) { | |
| args.columns = arg.slice("--columns=".length).split(",").map(s => s.trim()).filter(Boolean); | |
| continue; | |
| } | |
| if (arg === "-h" || arg === "--help") { | |
| args.help = true; | |
| continue; | |
| } | |
| throw new Error(`Unknown argument: ${arg}`); | |
| } | |
| return args; | |
| } | |
| function getByPath(obj, keyPath) { | |
| let cur = obj; | |
| for (const part of keyPath.split(".")) { | |
| if (cur == null || typeof cur !== "object") { | |
| return ""; | |
| } | |
| cur = cur[part]; | |
| } | |
| return cur == null ? "" : cur; | |
| } | |
| function csvEscape(value) { | |
| if (value == null) return ""; | |
| let s; | |
| if (typeof value === "object") { | |
| s = JSON.stringify(value); | |
| } else { | |
| s = String(value); | |
| } | |
| if (/[",\r\n]/.test(s)) { | |
| return `"${s.replace(/"/g, '""')}"`; | |
| } | |
| return s; | |
| } | |
| 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.columns || args.columns.length === 0) { | |
| usage(); | |
| process.exit(args.help ? 0 : 2); | |
| } | |
| await writeLine(args.columns.map(csvEscape).join(",")); | |
| const rl = readline.createInterface({ | |
| input: process.stdin, | |
| crlfDelay: Infinity, | |
| }); | |
| let lineNum = 0; | |
| let rows = 0; | |
| for await (const line of rl) { | |
| lineNum += 1; | |
| if (!line.trim()) { | |
| continue; | |
| } | |
| let record; | |
| try { | |
| record = JSON.parse(line); | |
| } catch (err) { | |
| throw new Error(`Invalid JSON on line ${lineNum}: ${err.message}`); | |
| } | |
| const values = args.columns.map((col) => csvEscape(getByPath(record, col))); | |
| await writeLine(values.join(",")); | |
| rows += 1; | |
| } | |
| console.error(`Done. Wrote ${rows} CSV 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