Skip to content

Instantly share code, notes, and snippets.

@Mifrill
Created September 29, 2025 12:13
Show Gist options
  • Select an option

  • Save Mifrill/3ba0b312b57dbafefbf6b2ab6ce946f2 to your computer and use it in GitHub Desktop.

Select an option

Save Mifrill/3ba0b312b57dbafefbf6b2ab6ce946f2 to your computer and use it in GitHub Desktop.
const fs = require('fs');
function parseCSVLine(line) {
const chars = line.split('');
const result = [];
let current = '';
let inQuotes = false;
const processChar = (char) => {
const isQuote = char === '"';
const isComma = char === ',';
const shouldSplit = isComma && !inQuotes;
inQuotes = isQuote ? !inQuotes : inQuotes;
shouldSplit && (result.push(current.trim()), current = '');
!shouldSplit && (current += char);
};
chars.forEach(processChar);
result.push(current.trim());
return result.map(field =>
field.replace(/^"(.*)"$/, '$1').replace(/""/g, '"')
);
}
const filePath = '2.csv';
const content = fs.readFileSync(filePath, 'utf-8');
const lines = content.trim().split('\n').filter(line => line.trim());
const headers = parseCSVLine(lines[0]);
const output = lines.slice(1).map(row => {
const values = parseCSVLine(row);
return headers.reduce((obj, header, idx) => {
obj[header] = values[idx] || '';
return obj;
}, {});
});
console.log(output);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment