Read Local File Line by Line Using JavaScript

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

I’m working on a demo web page using HTML and JavaScript, and I’d like to know how to use JavaScript to read a file line by line. Specifically, I want to read data from a local CSV file, process it line by line, and extract data from each row. Could someone explain how to accomplish this with JavaScript?

With my years of tinkering with JavaScript, I’ve found that the FileReader API is the go-to choice for reading local files directly in the browser. If you want to process each line of a file, here’s a simple example: prompt the user to select a file, read its content, and split it by line breaks (\n). This approach makes it super straightforward to implement JavaScript read file line by line functionality.

document.getElementById('fileInput').addEventListener('change', function () {
  const file = this.files[0];
  const reader = new FileReader();
  reader.onload = function () {
    const lines = reader.result.split('\n');
    lines.forEach(line => console.log(line));
  };
  reader.readAsText(file);
});

This is ideal for smaller files where you don’t need advanced file processing.

From my experience working on both front-end and back-end JavaScript, I’d recommend an alternative if your file is hosted locally on a development server. The fetch API is a great way to work with local files that are part of your project’s directory. It’s especially useful when building dynamic web apps. Using fetch allows you to easily load and process files line by line. Here’s how you can implement JavaScript read file line by line functionality:

fetch('data.csv')
  .then(response => response.text())
  .then(text => {
    const lines = text.split('\n');
    lines.forEach(line => console.log(line));
  });

Keep in mind that this method requires the file to be hosted and accessible via a URL.

When I’ve worked with server-side JavaScript, one of the most reliable tools has been Node.js’s readline module. It’s designed for efficient file reading, especially for large files where loading the entire content isn’t feasible. While this isn’t applicable for browser-based JavaScript, it’s incredibly effective in Node environments. Here’s how you can use JavaScript read file line by line on the server side:

const fs = require('fs');
const readline = require('readline');

const rl = readline.createInterface({
  input: fs.createReadStream('data.csv'),
  crlfDelay: Infinity,
});

rl.on('line', (line) => {
  console.log(line);
});

This approach keeps memory usage low and is perfect for processing files in real time.