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

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

    Try

    let a = document.createElement('a');
    a.href = "data:application/octet-stream,"+encodeURIComponent("My DATA");
    a.download = 'abc.txt';
    a.click();

    If you want to download binary data look here

    Update

    2020.06.14 I upgrade Chrome to 83.0 and above SO snippet stop works (reason: sandbox security restrictions) - but JSFiddle version works - here

    0 讨论(0)
  • 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);
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <button id="download">Download me</button>

    0 讨论(0)
  • 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();
    }
    
    0 讨论(0)
  • 2020-11-21 16:19

    Yes its possible Here the code is

    const fs = require('fs') 
    let data = "Learning how to write in a file."
    fs.writeFile('Output.txt', data, (err) => { 
          
        // In case of a error throw err. 
        if (err) throw err; 
    }) 

    0 讨论(0)
提交回复
热议问题