Line Filters in JavaScript
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 JavaScript that writes a capitalized version of all input text. You can use this pattern to write your own JavaScript line filters.
In this JavaScript version:
We use the
readline
module to create an interface for reading input line by line.The
readline.createInterface()
method wraps the unbufferedprocess.stdin
with a buffered reader, similar to howbufio.NewScanner()
is used in the original example.We use the
'line'
event to process each line of input as it’s read. This is equivalent to thescanner.Scan()
loop in the original.The
line.toUpperCase()
method is used to convert each line to uppercase, replacingstrings.ToUpper()
.We use
console.log()
to print the uppercased line, which is equivalent tofmt.Println()
.Error handling is done in the
'close'
event handler. If there was an error during reading, we print it to stderr and exit 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.
This JavaScript version provides the same functionality as the original, reading input line by line, converting each line to uppercase, and writing the result to stdout.