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

293
我想使用JavaScript向现有文件写入数据。 我不想将它打印到控制台。 我想实际写入数据到abc.txt。 我阅读了很多回答的问题,但是每个地方都在控制台上打印。 某些地方他们提供了代码,但是它不起作用。 所以,请问是否有任何人可以帮助我如何实际将数据写入文件。
我参考了代码,但它不起作用: 它会报错:

Uncaught TypeError: Illegal constructor

在谷歌浏览器上和

SecurityError: The operation is insecure.

在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将数据写入文件呢?


2
检查这个兄弟:https://dev59.com/ZnRB5IYBdhLWcg3wkH9N - welbornio
1
https://dev59.com/I27Xa4cB1Zd3GeqPoEl1 - Emilio Gort
11个回答

0

这里提供了一个单页面本地文件版本,当您需要脚本语言的额外处理功能时可以使用。

  1. 将下面的代码保存到文本文件中
  2. 将文件扩展名从“.txt”更改为“.html”
  3. 右键单击 > 选择“打开方式” > 记事本
  4. 按需编写文字处理程序,然后保存
  5. 双击HTML文件以在默认浏览器中打开
  6. 结果将在黑色框中预览,单击下载以获取结果文本文件

代码:

<!DOCTYPE HTML>
<HTML>
<HEAD>
</HEAD>
<BODY>
<SCRIPT>
    // do text manipulation here
    let string1 = 'test\r\n';
    let string2 = 'export.';
    
    // assemble final string
    const finalText = string1 + string2;
    
    // convert to blob
    const data = new Blob([finalText], {type: 'text/plain'});
    
    // create file link
    const link = document.createElement('a');
    link.innerHTML = 'download';
    link.setAttribute('download', 'data.txt');
    link.href = window.URL.createObjectURL(data);
    document.body.appendChild(link);
    
    // preview the output in a paragraph
    const htmlBreak = string => {
        return string.replace(/(?:\r\n|\r|\n)/g, '<br>');
    }
    const preview = document.createElement('p');
    preview.innerHTML = htmlBreak(finalText);
    preview.style.border = "1px solid black";
    document.body.appendChild(preview);
</SCRIPT>
</BODY>
</HTML>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接