Convert strings to Node.js streams and vice versa
Switch branches/tags
Nothing to show
Clone or download
Failed to load latest commit information.
ts Explain implementation choice for streamWrite(). May 6, 2018
.gitignore First commit. Apr 6, 2018
.npmignore First commit. Apr 6, 2018
LICENSE Initial commit Apr 6, 2018 New: onExit() May 5, 2018
package-lock.json 1.4.0 May 5, 2018
package.json 1.4.0 May 5, 2018
tsconfig.json New: onExit() May 5, 2018

stringio: convert strings to Node.js streams and vice versa

npm install @rauschma/stringio

Strings ↔︎ streams

See line A and line B:

import * as assert from 'assert';
import { StringStream, readableToString } from '@rauschma/stringio';

test('From string to stream to string', async () => {
  const str = 'Hello!\nHow are you?\n';
  const stringStream = new StringStream(str); // (A)
  const result = await readableToString(stringStream); // (B)
  assert.strictEqual(result, str);

StringStream: from string to stream

declare class StringStream extends Readable {
  constructor(str: string);

Used in line A.

readableToString: from stream to string

declare function readableToString(readable: Readable, encoding?: string): Promise<string>;

Default encoding is 'utf-8'.

Used in line B.

Reading stdin into a string

async function readStdin() {
  const str = await readableToString(process.stdin);
  console.log('STR: '+str);

Related npm packages

Asynchronous iterables

chunksToLinesAsync: async iterable over chunks to async iterable over lines

declare function chunksToLinesAsync(chunks: AsyncIterable<string>): AsyncIterable<string>;

Each line includes the line break at the end (if any – the last line may not have one).

Example (starting with Node.js v.10, readable streams are asynchronous iterables):

const fs = require('fs');
const {chunksToLinesAsync} = require('@rauschma/stringio');

async function main() {
  const stream = fs.createReadStream(process.argv[2]);
    // Works, too: const stream = process.stdin;
  for await (const line of chunksToLinesAsync(stream)) {

Promisified writing to streams

declare function streamWrite(
  stream: Writable,
  chunk: string | Buffer | Uint8Array,
  encoding = 'utf8')
  : Promise<void>;

declare function streamEnd(
  stream: Writable)
  : Promise<void>;


await streamWrite(someStream, 'abc');
await streamWrite(someStream, 'def');
await streamEnd(someStream);

onExit(childProcess): wait until a child process is finished

export declare function onExit(childProcess: ChildProcess): Promise<void>;


const childProcess = child_process.spawn(···);
await onExit(childProcess);

Errors emitted by childProcess or a non-zero exit code reject the Promise returned by onExit().

String helper function

chomp: remove a line break at the end of a line

declare function chomp(line: string): string;

Further reading

The following 2ality blog posts use stringio: