I want to read a certain amount of lines from a text file, and with them to create an object after reading the lines using JavaScript

Viewed 128

okay, so this is my requirement: The application must read each line from the text file. A class can be used so that after reading a certain number of lines an object is created (in this way the application is more clearly structured). After reading a data set that corresponds to a student's data, it will add this data set to a string (separate so that it is presented in consecutive rows).

So i have these information of 2 students which are one under the other like in the picture below but without the name address etc.(it doesn't show quite right in here).

Ebonie Rangel 7175 Yukon Street (507) 833-3567 Geography Keenan Ellwood 2 Elm Lane (894) 831-6482 History

which are in that file. and after reading every line, I am supposed to add Name in front of the first line, Address in front of the second.. phone and Course and so on. The result should look like this:

enter image description here

This is what i have for now (I have to use Fetch to get to the file, async and await. or with Promise)

let button = document.getElementById("text-button");
let textArea = document.getElementById("text-area");

button.addEventListener("click", function () {
  getData();
});

//cod fetch
async function getData() {
  try {
    let response = await fetch('fileName.txt');
    if (response.status !== 200) {
      throw new Error("Error while reading file");
    }
    let text = await response.text();
    textArea.innerHtml = text;
  } catch (err) {
    textArea.innerHTML = 'Problem occurred: ' + err.message;
  }
}

please help! I am stuck since forever on this.

2 Answers

Since you're pulling from a .txt file I think its important to understand the line breaks being used in the file. Here's a decent link I found that says all you need at the top of the article: End of Line or Newline Characters

I opened up the .txt file in Notepad++ like the article recommended and saw this:

Notepad++ View or Input File

The [CR][LF] being displayed after each line means that the newline characters used are \r\n.

When you understand that you realize you can use those line breaks to separate your string at each line break.

Here's the MDN for String.split() String.prototype.split()

String.split('\r\n') will return an Array of items, specifically the strings that were between but not including the \r\n characters.

Let's add this to the getData function:

let button = document.getElementById("text-button");
let textArea = document.getElementById("text-area");

button.addEventListener("click", function () {
  getData();
});

//cod fetch
async function getData() {
  try {
    let response = await fetch('fileName.txt');
    if (response.status !== 200) {
      throw new Error("Error while reading file");
    }
    let text = await response.text();
    
    //New stuff:
    let arrayOfText = text.split('\r\n');
    //Now we could add what we want before the text.
    //We need to do every 4 lines so lets use this as a chance to learn % better
    arrayOfText = arrayOfText.map((textItem, index) => {
        let remainder = (index) % 4        //This will return 0, 1, 2, 3

    //switch but you could use anything
        switch (remainder) {
            case 0:
                textItem = 'Name: ' + textItem + '\r\n';
                break;
            case 1:
                textItem = 'Address: ' + textItem + '\r\n';
                break;
            case 2:
                textItem = 'Phone: ' + textItem + '\r\n';
                break;
            case 3:
                textItem = 'Course: ' + textItem + '\r\n\r\n';    //two here to separate the groups
                break;
        //we need a default so lets make it just return textItem if something goes wrong
            default:
                break;

        };

        //Our new array has all the info so we can use 
        //Array.prototype.join('') with an empty string to make it a string.
        //We need those old line breaks though so lets put them 
        //in the switch returns above.
    
        text = arrayOfText.join('');

        //End of my changes/////////////

    textArea.innerHtml = text;
  } catch (err) {
    textArea.innerHTML = 'Problem occurred: ' + err.message;
  }
}

I hope this works out for you. Its not the most glamorous solution but its a good learning solution because it uses only things you learn early on in your studies.

Let me know if I can clarify anything!

async function getData() {
  try {
    let response = await fetch('https://v-dresevic.github.io/Advanced-JavaScript-Programming/data/students.txt');
    if (response.status !== 200) {
      throw new Error("Error while reading file");
    }
    let text = await response.text();
    const lines = text.split('\n');
    const CHUNK_SIZE = 4;
    textArea.innerHTML = new Array(Math.ceil(lines.length / CHUNK_SIZE))
      .fill()
      .map(_ => lines.splice(0, CHUNK_SIZE))
      .map(chunk => {
        const [Name, Address, Phone, Course] = chunk;
        return {Name, Address, Phone, Course};
      })
      .reduce((text, record) => {
        text += Object.keys(record).map(key => `${key} ${record[key]}`).join('\n') + '\n';
        return text;
      }, '');

  } catch (err) {
    textArea.innerHTML = 'Problem occurred: ' + err.message;
  }
}
Related