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:

  1. We use the readline module to create an interface for reading input line by line.

  2. The readline.createInterface() method wraps the unbuffered process.stdin with a buffered reader, similar to how bufio.NewScanner() is used in the original example.

  3. We use the 'line' event to process each line of input as it’s read. This is equivalent to the scanner.Scan() loop in the original.

  4. The line.toUpperCase() method is used to convert each line to uppercase, replacing strings.ToUpper().

  5. We use console.log() to print the uppercased line, which is equivalent to fmt.Println().

  6. 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.