menu-button

File Handling Operations

Functions for reading from files

While JavaScript does have an API for reading from local files stored on your own computer (which later tasks on this page will look it), JavaScript is not able to directly access files on a server, e.g. on DrFrostMaths! For the purposes of this tutorial, we have provided a simple function, fileOpen(fileName, access) which will allow you to read from a limited number of files on this server.

For example, to read from the file countries.txt and display each line (containing a single country) on the console:


var file = fileOpen('countries.txt', 'r');
while(!file.endOfFile()) {
    console.log(file.readLine());
}

What's going on here?

  • The first argument of fileOpen is the file we wish to read from. The second argument is whether we want to read from the file ('r') or write to the file ('w').
  • This returns a JSON representing access to the file, which the code has assigned to the variable file.
  • One method is file.endOfFile(), which returns false if there are more lines we can read, and true if we are at the end of the file and hence can't read any more lines.
  • file.readLine() returns the next line from the file being read, returning a string. You can do anything you like with this string, but above we chose to output it to the console.

Try running it:

Reset to Original Code     Fullscreen

The following files you are allowed to access on this page:

  • topschools.txt: A list of all schools, as of June 2nd 2019, that have at least 300,000 points on DrFrostMaths. Each line contains the name of the school, the city/town, the country, what gender the students are (or 'Mixed') and the number of points. There is one school per line, and each of these 5 values for each school are separated by tab characters, which are represented in code by \t. Read access only.
  • countries.txt: A list of all sovereign states in the world, one per line. Read access only.
  • myfile.txt: Only accessible to logged in users, but you can read and write to this file, and any changes will be preserved. Only you can access your file, but please do not include any personal information if you write to it.


Mini-Task #1: First and Last Letter

The file countries.txt has a list of all the countries of the world, one per line. Write code that searches for all countries within countries.txt that start and end in the same letter (ignoring capitalisation), and outputs each to the console.

Mini-Task #2: Writing to a File (Logged in Users Only)

As per above, only logged users, with a DFM account, may write to files. Each user is given a file myfile.txt and anything you write to it will be preserved.

If you wanted to write just 3 lines to your file, "Line 1", "Line 2" and "Line 3", use the following code:


var file = fileOpen('myfile.txt', 'w');
file.writeLine("Line 1");
file.writeLine("Line 2");
file.writeLine("Line 3");
file.close();

// Check we've actually written to the file!
file = fileOpen('myfile.txt', 'r');
console.log("New contents of myfile.txt:");
while(!file.endOfFile()) {
    console.log(file.readLine());
}

Now you have a go...

Reset to Original Code     Fullscreen

Mini-Task #3: Letter Count

The file countries.txt has a list of all the countries of the world, one per line. Write code that outputs the number of countries with each different number of letters, e.g. Num 4-letter countries: 10. You may wish to exclude space characters from letter counts. What is the most common number of letters?


Mini-Task #4: What countries is DFM popular in?

The file topschools.txt lists all schools with a total point score on DFM of at least 300,000 (as of 2nd June 2019). Each line contains the name of the school, the city/town, the country, what gender the students are (or 'Mixed') and the number of points. There is one school per line, and each of these 5 values for each school are separated by tab characters. You may wish to read the contents of the file first to see what it looks like.

Your task is to output a leaderboard of countries to the console. You should list each country and the total points score for that country. It may be helpful to use the string function line.split("\t"), which takes the string line and turns into an array, where the parts of the line are separated by tabs. For example "1,2,3".split(",") evalutes to ["1","2","3"].



Advanced: Reading Files From Your Computer

JavaScript has a library class FileReader which allows you to load files from your computer, and then handle them as you please.

The following code makes a HTML form input that allows you to select one or more files, before displaying the type of each file in a list:


<input type="file" id="myfiles1" name="myfiles1[]" multiple >
<ul id='filetypes'></ul>
<script>
document.getElementById('myfiles1').addEventListener('change', handleFileSelect);
function handleFileSelect(evt) {
    var files = evt.target.files; // array of files uploaded
    var fileTypes = [];
    for (var i = 0; i < files.length; i++) {
       var f = files[i];
       fileTypes.push(f.type);
    }
    document.getElementById('filetypes').innerHTML = "The file types were:

"+fileTypes.join(", "); } </script>

What's going on?

  • The <input> at the top is a HTML form element that allows you to select files on your desktop. The multiple keyword says that we're allowed to select more than one file. Putting [] at the end of the name is also needed so that the HTML knows we're potentially expecting multiple values.
  • document.getElementById(...) allows you to access something within your HTML, identified by its id tag.
  • addEventListener allows you to add a 'handler' when you interface with that HTML element. In this case we want to add a 'handler' for when we change the file(s) selected. It takes two arguments: the first is the type of event we're 'listening' for, in this case, whenever the user changes the file selected. The second is the name of the function to call when the event is triggered.
  • Our handleFileSelect method takes one parameter: a JSON evt which gives us information about the event that happened. In this particular case, it allows us to see what files were selected, using evt.target.files. This gives us an array (as multiple files might have been selected).
  • We iterate through these using a for loop. Each file object has an attribute type which is the file type. You could also use f.name for example to get the file name. These file types are added to the array fileTypes
  • fileTypes.join(", "); turns this array into a string, separating each element in the array with ", ". This is displayed on the console.

Try it below, and try modifying the code to see what else you can do with the files. You may want to Google the relevant JavaScript classes for extra documentation:

Reset to Original Code     Fullscreen


Advanced: Reading and Displaying Pictures from Your Computer

The following code (which includes some HTML) loads an image from your computer and then displays it:


<input type="file" id="myfiles2" name="myfiles2" />
<ul id='imglist'></ul>
<script>
document.getElementById('myfiles2').addEventListener('change', handleFileSelect);
function handleFileSelect(evt) {
    var files = evt.target.files; // any files chosen
    // Go through any files chosen and load image.
    for (var i = 0; i < files.length; i++) {
      var f = files[i];
      var reader = new FileReader();

      // Need to set the FileReader's onload method.
      // This handles what should happen when the file is read.
      reader.onload = (function(theFile) {
        return function(e) {
          // Render thumbnail.
          var li = document.createElement('li');
          li.innerHTML = '<img class="thumb" src="'+ e.target.result +
                            '" title="'+ escape(theFile.name) + '"/>';
          document.getElementById('imglist').appendChild(li);
        };
      })(f);

      // Read in the image file as a data URL.
      reader.readAsDataURL(f);
    }
}
</script>

Try it below. Note that the code will break if any of your chosen files are not images. Can you handle this appropriately?

Reset to Original Code     Fullscreen