Skip to content

Instantly share code, notes, and snippets.

@zavan
Created February 9, 2024 12:54
Show Gist options
  • Save zavan/2686bca80babebeacbffad6cd349b8ef to your computer and use it in GitHub Desktop.
Save zavan/2686bca80babebeacbffad6cd349b8ef to your computer and use it in GitHub Desktop.
Using node Readline.createInterface in a pipeline

pipeline accepts a function which receives the source as an argument and expects it to return a promise or async iterator, and the Interface object returned by Readline.createInterface can be used as an async iterator, so you can do this:

import { pipeline } from "node:stream";
import { createInterface } from "node:readline";

pipeline(
  process.stdin,
  (input) => createInterface({ input }),
  process.stdout,
  (err) => {
    if (err) {
      console.error('Pipeline failed.', err);
    } else {
      console.log('Pipeline succeeded.');
    }
  }
);

You could also wrap it to make it easier to reuse/setup options:

import { pipeline } from "node:stream";
import { createInterface } from "node:readline";

function createReadlineIterator(options = { crlfDelay: Infinity }) {
  return (input) => createInterface({
    input,
    ...options
  });
}

pipeline(
  process.stdin,
  createReadlineIterator(),
  process.stdout,
  (err) => {
    if (err) {
      console.error('Pipeline failed.', err);
    } else {
      console.log('Pipeline succeeded.');
    }
  }
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment