通过首先从HTML页面的值创建文本文件来追加/编辑文本文件

Appending/editing to a text file by creating it first from values from HTML page

本文关键字:文件 文本 创建 追加 编辑 HTML      更新时间:2023-09-26

我有一些值来自json通过套接字调用通过我的html页面上的硬件,现在这些值正在不断改变超过3秒的持续时间。我想创建一个文本文件,可以附加值(而不是替换它们)到这些不断变化的值。我所做的是一个叫做变化事件的函数,每次触发变化事件时都会创建一个新的文本文件。我想要的是创建一个单独的文件,并在其中附加值,现在发生的是每次值改变时它都会创建一个新文件。我的代码如下:

saveTextAsFile:function(d)
{
    console.log("data sent is",d);
    var textToWrite = d;
    var textFileAsBlob = new Blob([textToWrite], {type:'text/plain'});
    var fileNameToSaveAs = "testdata.txt";
    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();
},
 destroyClickedElement: function(event)
{
    document.body.removeChild(event.target);
}

因为变量textFileAsBlob是Blob对象,所以不能更改。

Blob对象表示具有不可变原始数据的类文件对象。Blob - Web API接口| Mozilla Developer Network

因此,您应该在创建文件之前用Javascript完成所有的连接工作,或者您应该在服务器端对文件进行处理。