Now write the function to update a file in a Document Library.
function updateFile() {
targetList = list.getByTitle("MyDocumentLibrary");
fileUpdate = new SP.FileCreationInformation();
var fileName = document.getElementById("txtFileName").value; //gets the file name
fileName = fileName + ".txt";
fileUpdate.set_url(fileName);
fileUpdate.set_content(new SP.Base64EncodedByteArray());
//set the overwrite attribute to true to update the file content.
fileUpdate.set_overwrite(true);
fileContent = document.getElementById("txtFileContent").value; //gets the file contents.
for (var content = 0; content < fileContent.length; content++) {
fileUpdate.get_content().append(fileContent.charCodeAt(content)); //add the text content to the file.
}
//update a file instance
var updateFileData = targetList.get_rootFolder().get_files().add(fileUpdate);
context.load(updateFileData);
context.executeQueryAsync(onFileUpdationSuccess, onFileUpdationSuccess);
}