Line Filters in TypeScript

A line filter is a common type of program that reads input on stdin, processes it, and then prints some derived result to stdout. grep and sed are common line filters.

Here’s an example line filter in TypeScript that writes a capitalized version of all input text. You can use this pattern to write your own TypeScript line filters.

import * as readline from 'readline';

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false
});

rl.on('line', (line) => {
  // Convert the line to uppercase
  const ucl = line.toUpperCase();

  // Write out the uppercased line
  console.log(ucl);
});

rl.on('close', () => {
  // Check for errors during reading
  if (rl.closed) {
    console.error('Error: Input stream closed unexpectedly');
    process.exit(1);
  }
});

In this TypeScript version, we use the readline module to read input line by line. The createInterface function wraps the standard input stream, similar to how the Go version uses a buffered scanner.

We set up an event listener for the ’line’ event, which is triggered each time a new line is read. Inside this listener, we convert the line to uppercase and print it.

We also set up a ‘close’ event listener to check for any errors that might occur during reading. If the readline interface is closed unexpectedly, we print an error message to stderr and exit the program with a non-zero status code.

To try out our line filter, first make a file with a few lowercase lines.

$ echo 'hello'   > /tmp/lines
$ echo 'filter' >> /tmp/lines

Then use the line filter to get uppercase lines.

$ cat /tmp/lines | ts-node line-filters.ts
HELLO
FILTER

Note that we’re using ts-node to run our TypeScript file directly. If you don’t have ts-node installed, you can compile the TypeScript to JavaScript first and then run it with Node.js:

$ tsc line-filters.ts
$ cat /tmp/lines | node line-filters.js
HELLO
FILTER

This example demonstrates how to create a simple line filter in TypeScript, reading from standard input, processing each line, and writing to standard output.