1

I am trying to read a local file and have each line as an index in an array using JavaScript. I have been searching for the past 20 minutes and either I'm stupid or there really isn't an answer that pertains to my problem (...but it's probably the former :P). I am really new to JavaScript so if you have an answer could you please comment the code just to I know what's going on?

Also, from the searching I've done on the internet some people said JavaScript can't read local file for security reasons so if that is correct is there another language I can use? I'm a bit familiar with PHP if that is an option, which I doubt it is.

EDIT

As per thg435's question, I'll explain what I am trying to accomplish.

My project is to analyze a BUNCH of water quality data that has been collected by the Ontario gov't (which I've done) and display it in some way. I have chosen to display it on a webpage using the Google Maps API. I currently have a file of chemicals that were found. Each line is a different chemical. I would like to read the file in an array then create an option menu displaying the chemicals in the array.

Also, the local file I would like to read will the be the same name and location all the time. I have seen people have boxes where the user clicks and chooses their file or to drag and drop but that's not what I'm looking for.


I don't think I explained this properly. I have a file in the same directory as my HTML and JavaScript files that contains words. Example:

Line 1: "Iron" Line 2: "Aluminum" Line 3: "Steel"

etc...

I would like to read the file and parse each line into a different index in an array. I don't want the user to be able to choose which file to read using the <input ... /> thing.

tshepang
  • 12,111
  • 21
  • 91
  • 136
user3015565
  • 393
  • 3
  • 6
  • 16
  • 1
    [FileReader API](https://developer.mozilla.org/en-US/docs/Web/API/FileReader) – Charlie Jan 12 '14 at 19:03
  • 1
    This is a vague, if not off topic, question. You'll get better answers if you tell us what your project is all about: I guess reading a text file into an array is not the ultimate goal. – georg Jan 12 '14 at 19:03
  • @thg435 I just added what I would like to accomplish. – user3015565 Jan 12 '14 at 19:10
  • 1
    @levi I think you linked this same question... – user3015565 Jan 12 '14 at 19:13
  • Here a solution from http://stackoverflow.com/questions/14446447/javascript-read-local-text-file – levi Jan 12 '14 at 19:14
  • @levi I looked at the accepted answer huses `XMLHttpRequest()`. A quick search told me the aforementioned function is for communicating with a server. Both the HTML and JavaScript filse are local for me. – user3015565 Jan 12 '14 at 19:18
  • I've updated my answer. It now contains a basic demo of both drag-and-drop file reading, and input file reading. You should check it out. – Joeytje50 Jan 12 '14 at 19:26
  • In response to your edit "I don't want the user to be able to choose which file to read", if that'd be possible, it'd be the worst security issue ever. That would render all privacy you have 0 when you'd visit your site, since your site would be able to pick and choose which files of yours to read. Unless with "local files" you don't mean "files on the user's computer", but "files on the server", this is just completely impossible. You can't read the user's files without their permissions. – Joeytje50 Jan 12 '14 at 19:56

2 Answers2

3

You're going to want to take a look at the FileReader API. This should allow you to read the text of a local file via readAsText(). This won't work in every browser but should work in all modern browser. You can see which browsers support it here.

Example:

<input id="file" type="file" />
var filesInput = document.getElementById("file");
filesInput.addEventListener("change", function (event) {
    var files = event.target.files;
    var file = files[0];
    var reader = new FileReader();
    reader.addEventListener("load", function (event) {
        var textFile = event.target;
        alert(textFile.result);
    });
    reader.readAsText(file);
});

It's not possible to invoke the FileReader API without user interaction. Consequently, your user would have to select whatever file to load in order for it to be read in pure JS. Since I'm assuming this will be up on a server, why not just put the list of chemicals also up on the server and GET the JSON encoded array of the results. Then you can decode them with Javascript.

Charlie
  • 11,380
  • 19
  • 83
  • 138
  • Just to confirm... `text` is the array where the lines of the file are stored and `file` would be the file directory? – user3015565 Jan 12 '14 at 19:15
1

You can access local files in 2 ways that I know of. The first way is making the user drag-and-drop the files onto the page, and using an <input type="file"> tag.

For the former, you would need to do the following:

addEventListener('dragover', function(e){e.preventDefault();});
addEventListener('drop', function(e) {
    eventHandler.call(e.dataTransfer||e.clipboardData);
    e.preventDefault();
});

For the latter, you'd need to add an event listener for the change event on the input:

document.getElementById('upload').addEventListener('change', eventHandler)

And for both, you'd need to have this as a basic callback function:

function eventHandler() {
    var file = this.files[0]; //get the files
    var reader = new FileReader(); //initiate reader
    reader.onloadend = callbackFn; //set event handler
    reader.readAsText(file); //initiate reading of files
    if (this.id) { //only run if this is the input
        var id = this.id; 
        this.outerHTML = this.outerHTML; //this resets the input
        document.getElementById(id).addEventListener('change', eventHandler); //reattach event handler
    }
    function callbackFn(e) {
        document.getElementById('output').value = e.target.result; //output it to a textarea
    }
}

Here is a demo where the text contents (that what you see when opening it in notepad) of any file you drop in it, or any file you select from the input, is put in the textarea.

For more information, see https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications.

Joeytje50
  • 18,636
  • 15
  • 63
  • 95
  • 1
    Thanks but I'm more looking for a fixed file location. Not something where the user chooses a file to read. – user3015565 Jan 12 '14 at 19:21
  • 1
    @user3015565 you can't automatically retrieve files from a viewer's computer. The user ALWAYS has to give you permission to read the files by selecting the files on your site. The script I provided is the simplest way it would be possible to read local files. There's simply no other way of doing it. PS: if it would be possible for any site to automatically retrieve any file it wants from a user's computer, then any site could go through any file it wants on your computer. That's incredibly insecure. – Joeytje50 Jan 12 '14 at 19:28