samedi 20 juillet 2019

How to open/save and edit a .txt file?

I have this project where I have to build a text editor, save the file as .txt and also being able to open it and make some changes.

I'm trying to do this with Javascript and I'm having some trouble with this part, I already have the code for creating the file and open it but if I try to open a file and edit something I can't save to the same file, it creates another one.

I've done some research and I think is not possible to edit a file from Javascript. I'm open to any suggestion at this point on how to accomplish this.

I used the js library FileSaver and the File API from HTML5

function showFile() {
  const preview = document.getElementById('fuenteTextarea');
  const file = document.querySelector('input[type=file]').files[0];
  const reader = new FileReader();

  var textFile = /text.*/;

  if (file.type.match(textFile)) {
    reader.onload = function(event) {
      preview.innerHTML = event.target.result;
    };
  } else {
    preview.innerHTML = 'El archivo no es .txt';
  }
  reader.readAsText(file);
}


function saveStaticDataToFile() {
  const userInput = document.getElementById('fuenteTextarea').value;
  const blob = new Blob([userInput], { type: 'text/plain;charset=utf-8' });
  const namefile = document.getElementById('nombreArchivo').value;
  if (namefile === '') {
    alert('Recuerde el nombre del archivo');
  } else {
    saveAs(blob, `${namefile}.txt`);
  }
}

Aucun commentaire:

Enregistrer un commentaire