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:
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:
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:
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.
- Looping Over Lines: The
for...ofloop processes each line in thelinesarray. You may explicitly declarelineas astringfor 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:
