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.
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.
Then use the line filter to get uppercase lines.
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:
This example demonstrates how to create a simple line filter in TypeScript, reading from standard input, processing each line, and writing to standard output.