JavaScript – How to read through a text file…

In this project we are looking at how to read through a text file using JavaScript. We will store a list of pupils in a text file. We are going to read through this list display its content on the webpage, one line at a time.

Step 1:

Using notepad, create a CSV file called ClassList.csv (Instead of using comma we use a pipe | as a separator)

John|Lennon|Male
Katy|Perry|Female
Robbie|Williams|Male
Amy|MacDonald|Female

 

Step 2:

Create an HTA application (See our blog post about HTA application).

Step 3:

Add the following code somewhere in the body section of the page:

<input type="button" onClick="Javascript: displayClassList();" value="Display Class List" />
<div id="searchResults"></div>

Step 4:

Add the following Javascript  code in the head section of the page (using as <SCRIPT> tag):

function displayClassList() {

var path="ClassList.csv"
var fso = new ActiveXObject('Scripting.FileSystemObject'),
iStream=fso.OpenTextFile(path, 1, false);

document.getElementById("searchResults").innerHTML="";

while(!iStream.AtEndOfStream) {
    var line=iStream.ReadLine();
    document.getElementById("searchResults").innerHTML += line + "<br/>";
}

iStream.Close();
}

The purpose of this code is to stream through the text file, which means to read it one line at a time.

Your challenge


Use and tweak this code to only display the boys from your class list.

Did you like this challenge?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.

As you found this challenge interesting...

Follow us on social media!