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.
const readline = require('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.input.errored) {
console.error('error:', rl.input.errored);
process.exit(1);
}
});
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.
$ echo 'hello' > /tmp/lines
$ echo 'filter' >> /tmp/lines
Then use the line filter to get uppercase lines.
$ cat /tmp/lines | node line-filters.js
HELLO
FILTER
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.