Skip to content Skip to sidebar Skip to footer

Javascript - Reading Urls From A File And Saving Them As Elements In An Array

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

Solution 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:

<inputid="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/FileListvar f = this.files[0]; // event.target.files[0] works too// Need an instance of this API for asynchronous file I/O.var fr = newFileReader();

  // 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/resultvar textInFile = this.result; // event.target.result works too// String.prototype.split with newline character argumentvar 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);
});

Solution 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

<inputtype="file">

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

Post a Comment for "Javascript - Reading Urls From A File And Saving Them As Elements In An Array"