Skip to content

Instantly share code, notes, and snippets.

@benshimmin
Created September 4, 2012 06:01
Show Gist options
  • Save benshimmin/3617435 to your computer and use it in GitHub Desktop.
Save benshimmin/3617435 to your computer and use it in GitHub Desktop.
How to read a drag-and-dropped file line by line (works in Chrome at least)
# I needed to handle CSV files exported from Excel. The following madness ensued.
# (I actually thought this would be easier than handling it on the server.
# How wrong I was.)
#
# Summary:
# Most of the FileReader.read* methods will - in Chrome at least - give you a string
# without line-breaks. This is basically useless when you're working with a CSV file.
# However, if you read the data as an ArrayBuffer, you can actually see the line-breaks
# and create lines that way.
#
# Caveats:
# * Only tested in Chrome... your browser needs to support typed arrays (yes, JavaScript
# sort of has those).
# * This probably doesn't work with non-ASCII characters. :-)
class LineParser
# let's assume you've handled all the file dropping stuff...
read : =>
reader = new FileReader
reader.onload = @bufferToLines
# @file would be event.dataTransfer.files[0] - your dropped file
reader.readAsArrayBuffer @file
bufferToLines : (event) =>
# an array buffer
buf = event.target.result
# a typed array of 8-bit ints
ibuf = new Int8Array buf
len = ibuf.length - 1
# 2D array holding arrays of chars
arrays = [[]]
count = 0
# iterate through the array buffer
for i in [0..len]
charCode = ibuf[i]
# this is a new line, so add a new char-holder array
# and increment the counter
if charCode is 13
arrays.push []
count++
# push into the appropriate array the actual char
arrays[count].push String.fromCharCode(charCode)
# array holding strings for each actual line
@lines = []
# iterate through each array and join its contents into a line
@lines.push arr.join("") for arr in arrays
# Done. Now you can have all kinds of fun with @lines!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment