Garrett
Garrett

Reputation: 261

Storing content from imported .txt in a JS variable

I want to be able to store the contents from an imported text file in a JS variable. Could someone please show me how I would go about doing this by using the JSFiddle example I have created? https://jsfiddle.net/495v0bxf/. Currently in the JSFiddle, you can select a document and display the contents.

I know the content can be accessed in the reader variable under 'result':

var reader = new FileReader();
console.log("reader: ", reader);

But I want the content to be stored in say:

var txtContent = 

Upvotes: 0

Views: 462

Answers (2)

Abhishek K. Upadhyay
Abhishek K. Upadhyay

Reputation: 1032

This will help you.. It has all the examples which will guide you to read the content and store in variable.

http://www.html5rocks.com/en/tutorials/file/dndfiles/

Thanks

Upvotes: 0

James Monger
James Monger

Reputation: 10665

As in your example, you need to store evt.target.result in the variable.

var reader = new FileReader();
var txtContent;

var doSomeStuff = function () {
    console.log("The text content was " + txtContent);
};

// If we use onloadend, we need to check the readyState.
reader.onloadend = function(evt) {
    if (evt.target.readyState == FileReader.DONE) { // DONE == 2
        txtContent = evt.target.result;
        doSomeStuff();
    }
};

As you can see, when doSomeStuff is called, txtContent is populated with the text loaded from the file.

Upvotes: 2

Related Questions