是否可以只使用JavaScript将数据写入文件?

是否可以只使用JavaScript将数据写入文件?,javascript,html,Javascript,Html,我想使用JavaScript将数据写入现有文件。 我不想在控制台上打印它。 我想将数据写入abc.txt。 我读了很多回答的问题,但每一个地方,他们都打印在控制台上。 在某些地方,他们给出了代码,但它不起作用。 所以,请任何人都能帮助我如何将数据写入文件 我参考了代码,但它不起作用: 其给出错误: 未捕获类型错误:非法构造函数 论铬与铬 SecurityError:操作不安全 关于Mozilla var f = "sometextfile.txt"; writeTextFile(f, "Spo

我想使用JavaScript将数据写入现有文件。 我不想在控制台上打印它。 我想将数据写入
abc.txt
。 我读了很多回答的问题,但每一个地方,他们都打印在控制台上。 在某些地方,他们给出了代码,但它不起作用。 所以,请任何人都能帮助我如何将数据写入文件

我参考了代码,但它不起作用: 其给出错误:

未捕获类型错误:非法构造函数

论铬与铬

SecurityError:操作不安全

关于Mozilla

var f = "sometextfile.txt";

writeTextFile(f, "Spoon")
writeTextFile(f, "Cheese monkey")
writeTextFile(f, "Onion")

function writeTextFile(afilename, output)
{
  var txtFile =new File(afilename);
  txtFile.writeln(output);
  txtFile.close();
}

那么,我们是否可以只使用Javascript将数据写入文件?

对此有一些建议-

  • 如果您试图在客户端计算机上编写文件,则不能以任何跨浏览器的方式执行此操作。IE确实有方法使“受信任”的应用程序能够使用ActiveX对象读/写文件
  • 如果您试图将其保存在服务器上,那么只需将文本数据传递到服务器,并使用服务器端语言执行文件编写代码
  • 要在客户端存储一些相当小的信息,可以使用cookie
  • 使用HTML5API进行本地存储

  • 如果您谈论的是浏览器javascript,出于安全原因,您不能将数据直接写入本地文件。HTML5新API只能允许您读取文件

    但如果您想写入数据,并允许用户将其作为文件下载到本地。以下代码起作用:

        function download(strData, strFileName, strMimeType) {
        var D = document,
            A = arguments,
            a = D.createElement("a"),
            d = A[0],
            n = A[1],
            t = A[2] || "text/plain";
    
        //build download link:
        a.href = "data:" + strMimeType + "charset=utf-8," + escape(strData);
    
    
        if (window.MSBlobBuilder) { // IE10
            var bb = new MSBlobBuilder();
            bb.append(strData);
            return navigator.msSaveBlob(bb, strFileName);
        } /* end if(window.MSBlobBuilder) */
    
    
    
        if ('download' in a) { //FF20, CH19
            a.setAttribute("download", n);
            a.innerHTML = "downloading...";
            D.body.appendChild(a);
            setTimeout(function() {
                var e = D.createEvent("MouseEvents");
                e.initMouseEvent("click", true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
                a.dispatchEvent(e);
                D.body.removeChild(a);
            }, 66);
            return true;
        }; /* end if('download' in a) */
    
    
    
        //do iframe dataURL download: (older W3)
        var f = D.createElement("iframe");
        D.body.appendChild(f);
        f.src = "data:" + (A[2] ? A[2] : "application/octet-stream") + (window.btoa ? ";base64" : "") + "," + (window.btoa ? window.btoa : escape)(strData);
        setTimeout(function() {
            D.body.removeChild(f);
        }, 333);
        return true;
    }
    
    要使用它:


    download('文件内容','filename.txt','text/plain')

    您可以使用和在浏览器中创建文件。所有最近的浏览器

    您不能直接保存您创建的文件,因为这会导致大量安全问题,但您可以将其作为下载链接提供给用户。在支持“下载”属性的浏览器中,可以通过链接的名称建议文件名。与任何其他下载一样,下载文件的用户对文件名拥有最终发言权

    var textFile = null,
      makeTextFile = function (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);
    
        // returns a URL you can use as a href
        return textFile;
      };
    
    下面是一个使用此技术从
    textarea
    保存任意文本的示例

    如果您希望立即启动下载,而不是要求用户单击链接,则可以使用鼠标事件模拟鼠标单击链接,就像s所做的那样。我已经创建了一个使用这种技术的

      var create = document.getElementById('create'),
        textbox = document.getElementById('textbox');
    
      create.addEventListener('click', function () {
        var link = document.createElement('a');
        link.setAttribute('download', 'info.txt');
        link.href = makeTextFile(textbox.value);
        document.body.appendChild(link);
    
        // wait for the link to be added to the document
        window.requestAnimationFrame(function () {
          var event = new MouseEvent('click');
          link.dispatchEvent(event);
          document.body.removeChild(link);
        });
    
      }, false);
    

    使用上面()的用户@usablecode生成文件。 如果要自动下载文件,请将刚刚生成的
    textFile
    传递到此函数:

    var downloadFile = function downloadURL(url) {
        var hiddenIFrameID = 'hiddenDownloader',
        iframe = document.getElementById(hiddenIFrameID);
        if (iframe === null) {
            iframe = document.createElement('iframe');
            iframe.id = hiddenIFrameID;
            iframe.style.display = 'none';
            document.body.appendChild(iframe);
        }
        iframe.src = url;
    }
    

    上面的答案很有用,但它可以帮助您在单击按钮时直接下载文本文件。 在此代码中,您还可以根据需要更改
    文件名
    。这是HTML5的纯javascript函数。 为我工作

    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();
    }
    

    如果不可能使用新的
    Blob
    解决方案,这肯定是现代浏览器中的最佳解决方案,那么仍然可以使用这种更简单的方法,它对文件大小有限制:

    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);
    
    $('#下载')。在(“单击”,函数(){
    函数下载(){
    var jsonObject={
    “姓名”:“约翰”,
    “年龄”:31岁,
    “城市”:“纽约”
    };
    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(“下载”,文件名);
    pp.click();
    }
    setTimeout(函数(){
    下载()
    }, 500);
    });
    
    
    
    下载我
    我在这里找到了很好的答案,但也找到了更简单的方法

    创建blob和下载链接的按钮可以组合在一个链接中,因为link元素可以具有onclick属性。(反过来似乎不可能,将href添加到按钮不起作用。)

    您可以使用
    bootstrap
    将链接样式设置为按钮,除了样式设置之外,它仍然是纯javascript

    将按钮和下载链接结合起来还可以减少代码,因为需要的那些丑陋的
    getElementById
    调用更少

    此示例只需单击一次按钮即可创建文本blob并下载:

    <a id="a_btn_writetofile" download="info.txt" href="#" class="btn btn-primary" 
       onclick="exportFile('This is some dummy data.\nAnd some more dummy data.\n', 'a_btn_writetofile')"
    >
       Write To File
    </a>
    
    <script>
        // URL pointing to the Blob with the file contents
        var objUrl = null;
        // create the blob with file content, and attach the URL to the downloadlink; 
        // NB: link must have the download attribute
        // this method can go to your library
        function exportFile(fileContent, downloadLinkId) {
            // revoke the old object URL to avoid memory leaks.
            if (objUrl !== null) {
                window.URL.revokeObjectURL(objUrl);
            }
            // create the object that contains the file data and that can be referred to with a URL
            var data = new Blob([fileContent], { type: 'text/plain' });
            objUrl = window.URL.createObjectURL(data);
            // attach the object to the download link (styled as button)
            var downloadLinkButton = document.getElementById(downloadLinkId);
            downloadLinkButton.href = objUrl;
        };
    </script>
    
    
    //指向包含文件内容的Blob的URL
    var objUrl=null;
    //创建包含文件内容的blob,并将URL附加到下载链接;
    //注意:链接必须具有下载属性
    //此方法可以转到您的库
    函数exportFile(fileContent,downloadLinkId){
    //撤消旧的对象URL以避免内存泄漏。
    if(objUrl!==null){
    window.URL.revokeObjectURL(objUrl);
    }
    //创建包含文件数据且可通过URL引用的对象
    var data=newblob([fileContent],{type:'text/plain'});
    objUrl=window.URL.createObjectURL(数据);
    //将对象附加到下载链接(样式为按钮)
    var downloadLinkButton=document.getElementById(downloadLinkId);
    downloadLinkButton.href=objUrl;
    };
    
    试试看

    a=document.createElement('a');
    a、 href=“data:application/octet-stream,”+encodeURIComponent(“我的数据”);
    a、 下载='abc.txt';
    
    a、 单击()这是可能的 代码在这里

    const fs=require('fs'))
    让data=“学习如何写入文件。”
    fs.writeFile('Output.txt',data,(err)=>{
    //如果出现错误,抛出err。
    如果(错误)抛出错误;
    })

    检查此处的Blob文档-为文件类型提供额外参数。默认情况下,它将生成.txt文件

    检查一下,兄弟:不知道为什么这会被否决。它对我有用。反对投票的人至少应该对投票被否决的原因发表评论!我没有投反对票,但实际上,对投票发表评论是不受欢迎的。用户应该对帖子内容发表评论,并对帖子内容进行投票,但
    const data = {name: 'Ronn', age: 27};              //sample json
    const a = document.createElement('a');
    const blob = new Blob([JSON.stringify(data)]);
    a.href = URL.createObjectURL(blob);
    a.download = 'sample-profile';                     //filename to download
    a.click();