【问题标题】:How to read file content in a javascript variable?如何读取 javascript 变量中的文件内容?
【发布时间】:2023-03-17 00:29:01
【问题描述】:

我有一个小脚本,可以在每 4 个字符后拆分 'var foo' 内的文本。它工作正常。 但我的实际数据在一个文本文件中,比如“a.txt”。如何在“var foo”中获取整个文件文本。并将拆分输出写入另一个文本文件?

var foo = "this is sample text !!!"; 
var arr = [];
for (var i = 0; i < foo.length; i++) {
    if (i % 4 == 0 && i != 0)
        arr.push(foo.substring(i - 4, i));
    if (i == foo.length - 1)
        arr.push(foo.substring(i - (i % 4), i+1));          
}
document.write(arr);
console.log(arr);

【问题讨论】:

  • 我看不出问题标题、描述和提供的代码之间有任何重要关系。请尝试解释您的问题的上下文,例如您在哪里尝试执行此代码,在浏览器中,在 JS 开发的本机应用程序或服务器中。

标签: javascript


【解决方案1】:

要获取文件的内容,您需要使用输入标签选择一个文件。

<!DOCTYPE html>
<head>
  <meta charset="UTF-8">
</head>
<body>
  <input id="input" type="file" accept="text/plain">
  <script src="script.js"></script>
</body>

在更改事件中读取文件内容的好时机。

const input = document.querySelector("#input");

input.addEventListener("change", () => {
  const file = input.files.item(0);
});

要将文件的内容作为字符串读取,您需要对其进行转换。

function fileToText(file, callback) {
  const reader = new FileReader();
  reader.readAsText(file);
  reader.onload = () => {
    callback(reader.result);
  };
}

文件内容作为字符串将提供给回调函数。您可以创建一个链接并使用点击事件将字符串下载到文本文件中。

function save(content, fileName, mime) {
  const blob = new Blob([content], {
    tipe: mime
  });
  const url = URL.createObjectURL(blob);
  const a = document.createElement("a");
  a.href = url;
  a.download = fileName;
  a.click();
}

这是完整的代码

const input = document.querySelector("#input");

input.addEventListener("change", () => {
  const file = input.files.item(0);
  fileToText(file, (text) => {
    save(text, "fileName.txt", "text/plain");
  });
});

function fileToText(file, callback) {
  const reader = new FileReader();
  reader.readAsText(file);
  reader.onload = () => {
    callback(reader.result);
  };
}

function save(content, fileName, mime) {
  const blob = new Blob([content], {
    tipe: mime
  });
  const url = URL.createObjectURL(blob);
  const a = document.createElement("a");
  a.href = url;
  a.download = fileName;
  a.click();
}
<!DOCTYPE html>

<head>
  <meta charset="UTF-8">
</head>

<body>
  <input id="input" type="file" accept="text/plain">
  <script src="script.js"></script>
</body>

您可以在此处阅读有关在 JavaScript 中操作文件的更多信息:https://www.html5rocks.com/en/tutorials/file/dndfiles/

【讨论】:

    【解决方案2】:

    解决方案对我有帮助:

    How do I load the contents of a text file into a javascript variable?

    var client = new XMLHttpRequest();
    client.open('GET', '/foo.txt');
    client.onreadystatechange = function() {
    alert(client.responseText);
    }
    client.send();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-09-26
      • 2015-12-24
      • 2022-10-17
      • 1970-01-01
      • 2021-07-21
      • 2019-06-17
      • 2016-03-16
      相关资源
      最近更新 更多