I figured it out myself.
For some reason, using the onkeypress event, the event was being triggered and the function called before any characters were inserted into the TextArea, resulting in the file being written with an empty string.
The reason for the successful writes on subsequent attempts was that on subsequent key presses, characters were then present within the TextArea, and were successfuly written to the file.
I simply used another method to call the function after characters were present.