Skip to content

Instantly share code, notes, and snippets.

@dashedstripes
Created August 7, 2017 13:52
Show Gist options
  • Save dashedstripes/dbf98d1261bd832f2a7f3b7fae80fe90 to your computer and use it in GitHub Desktop.
Save dashedstripes/dbf98d1261bd832f2a7f3b7fae80fe90 to your computer and use it in GitHub Desktop.
let fs = require('fs')
let csv = fs.readFileSync('sample.csv', 'utf8')
let ERROR_MESSAGES = ['Invalid CSV', 'Invalid CSV, not enough lines']
function parseCSV(csv) {
let parsed = []
let headers = []
if(isValidCSV(csv)) {
csv.split('\n').forEach((line, index) => {
if(index == 0) {
headers = line.toLowerCase()
.replace(/-|\r|\(|\)/g, '')
.replace(/\s+/g, ' ')
.replace(/\s/g, '_')
.split(',')
}else {
let temp = {}
let words = line.replace(/(\r\n|\n|\r)/gm, '').split(',')
if(words.length == headers.length) {
words.forEach((word, index) => {
temp[headers[index]] = word
parsed.push(temp)
})
}else {
displayError(`Line: ${index + 1} is invalid CSV, please fix and try again.`)
}
}
})
}
return parsed
}
function isValidCSV(csv) {
let lines = csv.split('\n')
let isValid = false
try{
if(lines.length == 1) {
throw ERROR_MESSAGES[0]
}else {
lines.forEach((line) => {
let hasCommas = line.match(/(,)/)
if(hasCommas != undefined) {
isValid = true
}else {
throw ERROR_MESSAGES[1]
}
})
}
}catch(err) {
displayError(err)
}
return isValid
}
function displayError(err) {
console.log(err)
}
module.exports = parseCSV
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment