When I was doing one of my projects , I needed a javascript function to read from a file and print it line by line.
However, it is not possible in Javascript to read from local file system.
Thus, I made a work around, which is to read from a file by PHP, and then append a line break symbol at the end of each line.
And finally, I have this javascript “class” to read from “file” line by line.
It works similar to BufferedReader in Java.
Here is the function:
String.prototype.trim = function () {
return this.replace(/^\s*/, "").replace(/\s*$/, "");
}
//line breaker %lb%
function FileReader(file) {
var lineBreaker ="%lb%";
this.fileString = file.trim();
var cursor = 0;
var recorder = new Array();
//public methods
this.close = function () {
cursor = 0;
recorder = null;
fileString ="";
}
this.readLine = function () {
var value = null;
if(cursor == 0 ){
process();
}
if(cursor<recorder.length) {
value = getLine();
cursor++;
}
alert(value);
return value;
}
//private methods
var process = function () {
recorder = fileString.split(lineBreaker);
}
var getLine = function() {
return recorder[cursor];
}
}
To use this “class”, firstly you can pass a file which is a String (formatted by backend language with a defined line break):
var fileObj = FileReader(file);
And when you call fileObj.readLine() , it will return a line of content.
Please notice that , you have to append a line break symbol(eg. %lb% ), you can also change the line break symbol ,but make
sure you change it in Javascript class.
admin General Javascript file, javascript fileReader, read, read file