Skip to content

csv-loader.js

js
const isCSVFormat = file => file.type === 'text/csv'

const onload = (callback) => ({target: {result}}) => {
  const csvData = result
    .split(/\r\n|\n/)
    .map(line => line.split(','))
  callback(csvData)
}
const onerror = (callback) => () => callback()
const onabort = onerror
const csvToObj = csvFile => {
  return new Promise((resolve, reject) => {
    const reader = Object.assign(new FileReader(), {
      onload: onload(resolve),
      onabort: onabort(reject),
      onerror: onerror(reject),
    })
    reader.readAsText(csvFile)
  })
}

csv-loader.html

html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>CSV File</title>
</head>
<body>
<input type="file" accept=".csv" onchange="loadFile(this)">
<script src="csv-loader.js"></script>
<script>
  const loadFile = (self) => {
    const {files: [csvFile]} = self
    if (!isCSVFormat(csvFile)) {
      alert('CSV 파일이 아닙니다.')
      self.value = ''
      return
    }

    csvToObj(csvFile)
      .then(console.log)
      .catch(console.error)
  }
</script>
</body>
</html>