Complete Guide to Reading Local Text Files Line by Line Using JavaScript

Nov 22, 2025 · Programming · 10 views · 7.8

Keywords: JavaScript | File Reading | Line by Line Parsing | FileReader | CSV Processing

Abstract: This article provides a comprehensive guide on reading local text files and parsing content line by line in HTML web pages using JavaScript. It covers FileReader API implementation, string splitting methods for line processing, complete code examples, asynchronous handling mechanisms, and error management strategies. The article also discusses handling different line break characters, offering practical solutions for scenarios like CSV file parsing.

Introduction

In modern web development, handling local files is a common requirement, particularly in scenarios such as data import and file preview. JavaScript provides access to user local files through the File API, but it's important to note browser security restrictions—access is only granted when users actively select files.

Core Implementation Principles

The core of reading local files lies in the FileReader object, which offers methods for asynchronous file content reading. When a user selects a file via <input type="file">, we obtain a File object and then use FileReader to read its content.

Key steps include:

Complete Code Implementation

Below is the complete implementation code based on native JavaScript:

<input type="file" name="file" id="file">
<div id='output'>
  ...
</div>

<script>
const $output = document.getElementById('output')
document.getElementById('file').onchange = function() {
  var file = this.files[0];

  var reader = new FileReader();
  reader.onload = function(progressEvent) {
    // Read the entire file content
    const text = this.result;
    $output.innerText = text

    // Split and process by lines
    var lines = text.split('\n');
    for (var line = 0; line < lines.length; line++) {
      console.log(lines[line]);
    }
  };
  reader.readAsText(file);
};
</script>

Code Analysis and Optimization

In the above code, FileReader's readAsText method reads the file content as a string. In the onload callback, we use split('\n') to divide the text by line breaks, then process each line through a loop.

In practical applications, consider the differences in line break characters across operating systems. Windows systems use \r\n, while Unix/Linux systems use \n. Regular expressions can handle multiple line break types:

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

Asynchronous Handling and Error Management

FileReader operations are asynchronous, meaning we need to handle the read results in callback functions. Additionally, error handling should be added to manage file read failures:

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

Practical Application Scenarios

This technique is particularly suitable for:

Important Considerations

Ensure that JavaScript code executes after the file input element is rendered; otherwise, event listeners cannot be bound correctly. For large files, consider using stream reading or chunk processing to avoid memory issues.

Conclusion

By combining the FileReader API with basic string operations, we can easily implement reading and line-by-line parsing of local text files. This method is simple and effective, suitable for most web application scenarios, providing a convenient solution for data processing.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.