Reading Text Files Line-by-Line with TypeScript

Introduction and Context Setting

Welcome to this lesson, where we'll explore an essential technique in text data manipulation: reading files line-by-line with TypeScript. In many real-world applications, processing data one line at a time is crucial for effective data management, especially when handling large files like logs or data streams. By the end of this lesson, you'll understand how to efficiently read and process file data line-by-line, leveraging TypeScript's capabilities with Node.js.

Opening Files

In TypeScript, when using Node.js, we handle file operations with the fs module. To open a file and read its contents, we'll utilize fs.readFileSync(). However, TypeScript adds the advantage of type safety. Here's an example:

TypeScript
import * as fs from 'fs';

const filePath: string = 'input.txt';
const content: string = fs.readFileSync(filePath, 'utf-8');

In this example, filePath is explicitly declared as a string, indicating the location of your file, and content is a string containing the entire file's content, read synchronously.

Reading Files Line-by-Line

Reading a file line-by-line in TypeScript is straightforward. We'll use the split() method, but with explicit type annotations for clarity:

TypeScript
import * as fs from 'fs';

const filePath: string = 'input.txt';
const content: string = fs.readFileSync(filePath, 'utf-8');
const lines: string[] = content.split(/\r?\n/);

The regular expression /\r?\n/ is used to split the content into lines. It matches both UNIX (\n) and Windows-style (\r\n) line endings, ensuring compatibility across different text file formats. Here, lines is an array of strings, each representing a line from input.txt. For a file's content like:

text
Hello,
world
!

The lines array would be: ["Hello,", "world", "!"] after the split operation.

Iterating Over Lines and Cleaning Up Output

After obtaining your file lines in an array, you can iterate over them using a for...of loop.

TypeScript
import * as fs from 'fs';

const filePath: string = 'input.txt';
const content: string = fs.readFileSync(filePath, 'utf-8');
const lines: string[] = content.split(/\r?\n/);

for (const line of lines) {
  console.log(line.trim());
}
  • Looping Over Lines: The for...of loop processes each line in the lines array. You may explicitly declare line as a string for clarity: for (const line: string of lines).
  • Using trim(): This method removes leading and trailing whitespace, including newline characters, from each line.

The output will display each line from input.txt without unnecessary newlines:

text
Hello,
world
!
Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal