User Program Communication
Read from Text File in JavaScript
Used to read text files from the browser.
Syntax
//first, check if the File API is supported
if(window.File && window.FileReader && window.FileList && window.Blob){
var reader = FileReader(); //create FileReader object
reader.onLoad() = function(e) { //declare on load behaviour for the reader
var fileContent = reader.result;
}
reader.readAsText(file);
}
else {
//You cannot read from the file if the File API is not supported
}
Notes
The reader.onLoad() is a callback method that executes when a file is read. The readAsText function is called to specify the type of data read from the file. It takes in the file as the first parameter, and an optional second parameter to specify encoding type.
Example
if(window.File && window.FileReader && window.FileList && window.Blob){
var getNameFromFile = FileReader(); //getting name from a file
reader.onLoad() = function(e) { //declare on load behaviour for the reader
var name = reader.result;
}
getNameFromFile.readAsText(file);
}
else {
//You cannot read from the file if the File API is not supported
}