How to use JavaScript to read a local text file and read line by line?

Spread the love

To use JavaScript to read a local text file and read line by line, we use the FileReader constructor.

For instance, we write

const handleFiles = (input) => {
  const file = input.target.files[0];
  const reader = new FileReader();

  reader.onload = (event) => {
    const file = event.target.result;
    const allLines = file.split(/\r\n|\n/);
    allLines.forEach((line) => {
      console.log(line);
    });
  };

  reader.onerror = (event) => {
    alert(event.target.error.name);
  };

  reader.readAsText(file);
};

to create a FileReader object in the handleFiles function.

We get the selected file from input.target.files.

Then we set reader.onload to a function thet gets the read text string from event.target.result.

Then we call split to split the file string into an array of lines.

We call forEach to loop through each line.

And then we call readAsText to read the file as a text file.

Leave a Reply

Your email address will not be published. Required fields are marked *