JavaScript - 从文件中读取 URL 并将它们保存为数组中的元素

JavaScript - Reading URLs from a file and saving them as elements in an array

我的 javascript 技能很少,我想将文件的行作为字符串参数传递给预先编写的函数。基本上我想做的是读取这种格式的文件,每个 url 在自己的行上:

www.url1.com www.url2.com

...等等

如何读取本地文件并将每一行保存到字符串数组?

非常感谢,如有不明之处请告诉我

查看 HTML5 文件 API。

有关示例,请参阅此博客 post:http://blog.teamtreehouse.com/reading-files-using-the-html5-filereader-api

虽然有限制,但必须通过

<input type="file">

所以你不能在用户不知情的情况下读取任意文件。

您可以通过查看 FileList, File, and FileReader 网络 API 来完成此操作。请注意,您的浏览器可能不支持这些 API,但大多数现代浏览器应该支持。您可以通过在 window 对象中查找它们的属性来检查它们是否存在。

我在下面添加了带有注释的示例代码。

HTML:

<input id="f" type="file">

JavaScript:

// This event listener is triggered when you open a file with the input button.
document.getElementById('f').addEventListener('change', function(event) {
  // Get File from FileList.
  // Documentation: https://developer.mozilla.org/en-US/docs/Web/API/FileList
  var f = this.files[0]; // event.target.files[0] works too

  // Need an instance of this API for asynchronous file I/O.
  var fr = new FileReader();

  // First create a function to handle the "onload" event.
  fr.onload = function(event) {
    // FileReader.result holds file contents
    // Documentation: https://developer.mozilla.org/en-US/docs/Web/API/FileReader/result
    var textInFile = this.result; // event.target.result works too
    // String.prototype.split with newline character argument
    var urls = textInFile.split('\n');
    console.log(urls);
  }

  // This performs asynchronous I/O and eventually triggers the "onload" event.
  // Default encoding is UTF-8.
  // Documentation: https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsText
  fr.readAsText(f);
});