Created
September 29, 2025 12:13
-
-
Save Mifrill/3ba0b312b57dbafefbf6b2ab6ce946f2 to your computer and use it in GitHub Desktop.
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
| 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