簡體   English   中英

編輯文件-純js

[英]Edit file - pure js

如何在純js中編輯文件(無節點)? 我得到一個帶有輸入字段的文件,並按如下方式讀取其文本:

var fileReader = new FileReader();
fileReader.readAsText(file);

fileReader.onload = function () {
    alert(this.result);
}

因此,非常簡單。 我試圖在網上尋找如何使用fileWriter的方法,但沒有成功。 我只需要編輯該文件中的文本並將其保存,該怎么辦?

您無法在瀏覽器中寫入文件,而必須使用node。

您可以讀取文本文件中的數據,在客戶端JavaScript(無Node)中對其進行修改,然后輸出並重新保存。 但是,它確實需要用戶交互。

我修改過的這是一個JS小提琴,雖然它不會讀取文件,但它會從某些文本輸出文件。

最初取自這個Stackoverflow問題

(function () {
    var textFile = null;
  function makeTextFile(text) {
    var data = new Blob([text], {type: 'text/plain'});

    // If we are replacing a previously generated file we need to
    // manually revoke the object URL to avoid memory leaks.
    if (textFile !== null) {
      window.URL.revokeObjectURL(textFile);
    }

    textFile = window.URL.createObjectURL(data);

    return textFile;
  }


  var create = document.getElementById('create');
  var textbox = document.getElementById('textbox');

    //create a click event listener
  create.addEventListener('click', function () {
    var link = document.getElementById('downloadlink');
    link.setAttribute('download', 'info.txt');
    //make the text file
    link.href = makeTextFile(textbox.value);
    link.style.display = 'block';
        //wait for the link to be rendered and then initiate a click to download the file
     window.requestAnimationFrame(function () {
      var event = new MouseEvent('click');
      link.dispatchEvent(event);
      document.body.removeChild(link);
    });
  }, false);

})();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM