import { promises as fs } from "fs"; function* getLinesFromString(source) { let lines = String(source || "").matchAll(/^.+$/gm); for (const [line] of lines) yield line; } function* getCsvValueFromLine(source, separator) { const line = String(source || ""); const sep = String(separator || ";"); let inString = false; let start = 0; for (var i = 0; i < line.length; i++) { const char = line[i]; if (i + 1 === line.length) { yield line.substring(start, i + 1); // or slice() } else if (!inString && char === sep) { yield line.substring(start, i); // or slice() start = i + 1; } else if (char === '"') { inString = !inString; } } } function decodeValue(val) { return trimChars(val.trim(), "\"").replace(/""/gm, "\""); } function trimChars(s, c) { if (c === "]") c = "\\]"; if (c === "^") c = "\\^"; if (c === "\\") c = "\\\\"; return s.replace(new RegExp("^[" + c + "]+|[" + c + "]+$", "g"), ""); } async function main() { console.log("running"); const data = await fs.readFile("input.csv"); const csv = data.toString(); for (const line of getLinesFromString(csv)) { console.log("======================") for (const value of getCsvValueFromLine(line, ",")) { console.log("value:", decodeValue(value)); } } console.log("finished"); } main();
577500cookie-checkJavascript parse CSV