Skip to content

zenflow/stream-line-reader

Repository files navigation

stream-line-reader

Read through a stream of lines on-demand

npm stats

CI status dependencies status Code Climate maintainability Known Vulnerabilities License: MIT

Installation

$ npm install stream-line-reader

Usage

const { spawn } = require('child_process');
const { StreamLineReader } = require('stream-line-reader');

async function example () {
  const child = spawn('my-calculator-program');
  const lines = new StreamLineReader(child.stdout);

  console.log(await lines.readUntil('Done startup'));
  // -> ['Starting...', 'Done startup']

  child.stdin.write('1+2\n');
  console.log(await lines.readUntil(/^Answer:/));
  // -> ['Question: 1+2', 'Calculating...', 'Answer: 3']

  child.stdin.write('3+4\n');
  console.log(await lines.readUntil(line => line.startsWith('Answer:')));
  // -> ['Question: 3+4', 'Calculating...', 'Answer: 7']

  child.stdin.end();
  console.log(await lines.readRemaining());
  // -> ['Bye!', '']
}

Instance can be created with a single stream, or an array of streams, in which case they are merged (interleaved), to be read as one stream.

If during a call to .readUntil() the stream ends without emitting a matching line, an error will be raised with details for debugging.

Instances also have a .readBuffered() method for when some time has passed and you just want to read whatever lines have become available. It takes no arguments and returns synchronously an array of lines.

About

Read through a stream of lines on-demand

Resources

Stars

Watchers

Forks

Packages

No packages published