Uploading file chunks using socket.io/node.js not working with non-text files

Just messing around with node.js, I am trying to get a file uploader working that chunks the file on the client side, sends pieces to the server via socket.io, and reassembles. It's a rather naive implementation, but just trying to learn. Currently if I submit a text file, it moves over and is reassembled correctly, but if I try to upload say an image file, the encoding is messed up and the file is corrupt.

I am reading on the client side as binary string, and the node fs encoding is set to binary. What else needs to happen?

Client Code

while(start < fileSize)
{
    var reader = new FileReader();
    reader.onload = function(e){
        var data = {
            "data" : e.target.result,
            "sequence" : chunkCount++
        };
        socket.emit("sendChunk", data, function(data){
            console.log("Confirmation recieved");
        });
        console.log("Log: Sent");
    };

    reader.onerror = function(e){
        alert(e.getMessage());
    };

    var blob = file.slice(start, end);
    reader.readAsBinaryString(blob);
    start = end;
    end = end + chunkSize;

}

Server Code

socket.on('sendChunk', function (data) {
    fs.appendFileSync(path + fileName, data.data, 'binary');
    console.log(data.sequence + ' - The data was appended to file ' + fileName);
});

Update

With the suggestion given, I updated the code to use base64 decoding. There is still some sequencing issues going on sometimes, but for the most part files are transferring correctly.

Client Code:

var data = {
    "data" : window.btoa(e.target.result),
    "sequence" : chunkCount++
};
socket.emit("sendChunk", data, function(data){
    console.log("Confirmation recieved");
});

Server Code:

var decoded =  new Buffer(data.data, 'base64').toString('binary');
fs.appendFileSync(path + fileName, decoded, 'binary');

socket.emit() is written in JavaScript and thus treats the payload as a JavaScript String. You are receiving garbled data on the server because in JavaScript strings are represented in UCS-2, and certain control characters are being escaped. In other words: a JavaScript string is not an Array of byte-sized characters, and it's not suitable for storing or transporting binary data.

The safest way to transmit your image is to encode the binary data as base64 on the client, and decode on the server with the Buffer class.