Skip to content

alanshaw/it-to-stream

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

34 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

it-to-stream

Build Status dependencies Status JavaScript Style Guide

Convert streaming iterables to Node.js streams

Install

npm i it-to-stream

Usage

const toStream = require('it-to-stream')

Convert source iterable to readable stream

// A streaming iterable "source" is just an (async) iterable
const source = (async function * () {
  for (const value of [1, 2, 3, 4]) yield Buffer.from(value.toString())
})()

const readable = toStream.readable(source)

// Now we have a readable stream, we can consume it by
readable.on('data', console.log)
// or
readable.pipe(writable)
// or
pipeline(readable, writable, err => console.log(err || 'done'))

Convert sink iterable to writable stream

// A streaming iterable "sink" is an (async) function that takes a "source"
// and consumes it.
const sink = async source => {
  for await (const chunk of source) {
    console.log(chunk.toString())
  }
}

const writable = toStream.writable(sink)

// Now we have a writable stream, we can pipe to it
fs.createReadStream('/path/to/file').pipe(writable)

Convert transform iterable to transform stream

// A streaming iterable "transform" is a function that takes a "source" and
// returns a "source".
const transform = source => (async function * () {
  for await (const chunk of source) {
    // Replace all space characters with dashes
    yield Buffer.from(chunk.toString().replace(/ /g, '-'))
  }
})()

const transform = toStream.transform(transform)

// Now we have a transform stream, we can pipe to and from it
fs.createReadStream('/path/to/file')
  .pipe(transform)
  .pipe(fs.createWriteStream('/path/to/file2'))

API

const toStream = require('it-to-stream')

toStream.readable(source, [options]): Readable

Convert a source iterable to a Readable stream.

options are passed directly to the Readable constructor.

toStream.writable(sink, [options]): Writable

Convert a sink iterable to a Writable stream.

options are passed directly to the Writable constructor.

toStream.transform(transform, [options]): Transform

Convert a transform iterable to a Transform stream.

options are passed directly to the Transform constructor.

toStream.duplex(duplex, [options]): Duplex

Convert a duplex iterable to a Duplex stream.

options are passed directly to the Duplex constructor.

Related

  • stream-to-it Convert Node.js streams to streaming iterables
  • it-pipe Utility to "pipe" async iterables together

Contribute

Feel free to dive in! Open an issue or submit PRs.

License

MIT © Alan Shaw

About

🚰 Convert streaming iterables to Node.js streams

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Contributors 4

  •  
  •  
  •  
  •