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

牧云@^-^@ 提交于 2020-01-04 07:28:06

问题


I have very little javascript skills and I would like to pass lines of a file as String arguments to a pre-written function. Basically what I want to do is read a file in this type of format, with each url on its own line:

www.url1.com www.url2.com

...And so on

How can I read a local file and save each line to a String array?

Thank you very much, and let me know if anything is unclear


回答1:


You can do this by looking at FileList, File, and FileReader web APIs. Note that your browser may not support these APIs, but most modern browsers should. You can check for their existence by looking for their properties in the window object.

I have added example code below with comments.

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



回答2:


Have a look at the HTML5 File API.

For an example see this blog post: http://blog.teamtreehouse.com/reading-files-using-the-html5-filereader-api

Although the limitation is, this must be used through a

<input type="file">

So you cannot just read arbitrary files, without the user knowing.



来源:https://stackoverflow.com/questions/33655538/javascript-reading-urls-from-a-file-and-saving-them-as-elements-in-an-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!