Skip to content

Instantly share code, notes, and snippets.

@brandonhimpfen
Created July 4, 2026 21:55
Show Gist options
  • Select an option

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

Select an option

Save brandonhimpfen/bc5ba2a4e78bc39058c68fc806bd17e6 to your computer and use it in GitHub Desktop.
Detect duplicate CSV headers or duplicate JSON object keys while streaming in Node.js, with no dependencies.
#!/usr/bin/env node
/**
* Detect duplicate CSV headers or duplicate JSONL keys while streaming.
*
* Usage:
* node node-detect-duplicate-fields.js input.csv --format=csv
* cat input.jsonl | node node-detect-duplicate-fields.js --format=jsonl
*
* Notes:
* - CSV mode checks only the header row.
* - JSONL mode checks duplicate keys within each JSON object line.
* - JavaScript's JSON.parse does not preserve duplicate keys, so JSONL mode
* uses a lightweight scanner before parsing.
* - No dependencies.
*/
const fs = require("fs");
const readline = require("readline");
function parseArgs(argv) {
const args = {
file: null,
format: "jsonl",
delimiter: ",",
};
for (const arg of argv.slice(2)) {
if (!args.file && !arg.startsWith("--")) args.file = arg;
else if (arg.startsWith("--format=")) args.format = arg.slice("--format=".length);
else if (arg.startsWith("--delimiter=")) args.delimiter = arg.slice("--delimiter=".length);
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-detect-duplicate-fields.js input.csv --format=csv
cat input.jsonl | node node-detect-duplicate-fields.js --format=jsonl
Options:
--format=csv|jsonl Input format (default: jsonl)
--delimiter=, CSV delimiter (default: ,)
`);
}
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 findDuplicates(values) {
const seen = new Set();
const duplicates = new Set();
for (const value of values) {
if (seen.has(value)) duplicates.add(value);
seen.add(value);
}
return [...duplicates];
}
// Lightweight scanner for duplicate JSON object keys.
// It tracks object nesting and detects repeated keys within the same object.
// This is intentionally small, not a full JSON parser.
function detectDuplicateJSONKeys(line) {
const stack = [];
const duplicates = [];
let i = 0;
function skipWhitespace() {
while (/\s/.test(line[i] || "")) i++;
}
function readString() {
let out = "";
i++; // opening quote
while (i < line.length) {
const ch = line[i];
if (ch === "\\") {
out += ch + (line[i + 1] || "");
i += 2;
continue;
}
if (ch === '"') {
i++;
return out;
}
out += ch;
i++;
}
return out;
}
while (i < line.length) {
const ch = line[i];
if (ch === "{") {
stack.push(new Set());
i++;
continue;
}
if (ch === "}") {
stack.pop();
i++;
continue;
}
if (ch === '"') {
const start = i;
const key = readString();
skipWhitespace();
if (line[i] === ":" && stack.length > 0) {
const current = stack[stack.length - 1];
if (current.has(key)) {
duplicates.push(key);
}
current.add(key);
}
// Continue after the string/key
if (i === start) i++;
continue;
}
i++;
}
return [...new Set(duplicates)];
}
async function runCSV(input, delimiter) {
const rl = readline.createInterface({ input, crlfDelay: Infinity });
let lineNum = 0;
for await (const line of rl) {
lineNum++;
if (!line.trim()) continue;
const headers = parseCSVLine(line, delimiter);
const duplicates = findDuplicates(headers);
if (duplicates.length > 0) {
console.error(`Duplicate CSV header(s): ${duplicates.join(", ")}`);
process.exitCode = 1;
} else {
console.error("No duplicate CSV headers found.");
}
return;
}
console.error("No CSV header row found.");
process.exitCode = 1;
}
async function runJSONL(input) {
const rl = readline.createInterface({ input, crlfDelay: Infinity });
let lineNum = 0;
let duplicateLines = 0;
for await (const line of rl) {
lineNum++;
if (!line.trim()) continue;
const duplicates = detectDuplicateJSONKeys(line);
if (duplicates.length > 0) {
duplicateLines++;
console.error(`Line ${lineNum}: duplicate key(s): ${duplicates.join(", ")}`);
}
}
if (duplicateLines > 0) {
console.error(`Done. Lines with duplicate keys: ${duplicateLines}.`);
process.exitCode = 1;
} else {
console.error("Done. No duplicate JSON keys found.");
}
}
async function main() {
const args = parseArgs(process.argv);
if (args.help || !["csv", "jsonl"].includes(args.format)) {
usage();
process.exit(args.help ? 0 : 2);
}
const input = args.file
? fs.createReadStream(args.file, { encoding: "utf8" })
: process.stdin;
if (args.format === "csv") {
await runCSV(input, args.delimiter);
} else {
await runJSONL(input);
}
}
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