Is it possible to write data to file using only JavaScript?

后端 未结 10 1309
梦如初夏
梦如初夏 2020-11-21 15:45

I want to Write Data to existing file using JavaScript. I don\'t want to print it on console. I want to Actually Write data to abc.txt. I read many answered que

10条回答
  •  盖世英雄少女心
    2020-11-21 16:17

    In the case it is not possibile to use the new Blob solution, that is for sure the best solution in modern browser, it is still possible to use this simpler approach, that has a limit in the file size by the way:

    function download() {
                    var fileContents=JSON.stringify(jsonObject, null, 2);
                    var fileName= "data.json";
    
                    var pp = document.createElement('a');
                    pp.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(fileContents));
                    pp.setAttribute('download', fileName);
                    pp.click();
                }
                setTimeout(function() {download()}, 500);
    

    $('#download').on("click", function() {
      function download() {
        var jsonObject = {
          "name": "John",
          "age": 31,
          "city": "New York"
        };
        var fileContents = JSON.stringify(jsonObject, null, 2);
        var fileName = "data.json";
    
        var pp = document.createElement('a');
        pp.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(fileContents));
        pp.setAttribute('download', fileName);
        pp.click();
      }
      setTimeout(function() {
        download()
      }, 500);
    });
    
    

提交回复
热议问题