代码之家  ›  专栏  ›  技术社区  ›  Johnson

编辑文件-纯js

  •  1
  • Johnson  · 技术社区  · 8 年前

    如何在纯js(没有节点)中编辑文件? 我得到一个带有输入字段的文件,我读取其文本如下:

    var fileReader = new FileReader();
    fileReader.readAsText(file);
    
    fileReader.onload = function () {
        alert(this.result);
    }
    

    所以,非常直截了当。我试图在网上看看如何使用fileWriter,但没有成功。 我只需要编辑文件中的文本并保存它,我该怎么做?

    2 回复  |  直到 8 年前
        1
  •  4
  •   Marcus Parsons    8 年前

    您可以读取文本文件中的数据,在客户端JavaScript(无节点)中修改它,然后输出并重新保存它。不过,它确实需要用户交互。

    This is a JS fiddle I modified that outputs the file from some text, although it does no reading of files.

    最初取自 this Stackoverflow question

    (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);
    
    })();
    
        2
  •  3
  •   Ben West    8 年前

    不能在浏览器中写入文件,必须使用节点。