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

后端 未结 10 1307
梦如初夏
梦如初夏 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:18

    Above answer is useful but, I found code which helps you to download text file directly on button click. In this code you can also change filename as you wish. It's pure javascript function with HTML5. Works for me!

    function saveTextAsFile()
    {
        var textToWrite = document.getElementById("inputTextToSave").value;
        var textFileAsBlob = new Blob([textToWrite], {type:'text/plain'});
        var fileNameToSaveAs = document.getElementById("inputFileNameToSaveAs").value;
          var downloadLink = document.createElement("a");
        downloadLink.download = fileNameToSaveAs;
        downloadLink.innerHTML = "Download File";
        if (window.webkitURL != null)
        {
            // Chrome allows the link to be clicked
            // without actually adding it to the DOM.
            downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);
        }
        else
        {
            // Firefox requires the link to be added to the DOM
            // before it can be clicked.
            downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
            downloadLink.onclick = destroyClickedElement;
            downloadLink.style.display = "none";
            document.body.appendChild(downloadLink);
        }
    
        downloadLink.click();
    }
    

提交回复
热议问题