dopatraman dopatraman - 1 year ago 83
CoffeeScript Question

How do I turn a String into a Readable Stream?

I'm trying to stream a string to another stream:

streamer = new stream.Transform objectMode: true
stringer = (string) ->
streamer._transform = (chunk, encoding, done) ->
@push string.split('').shift()

return streamer

streamer.on 'readable', ->
console.log 'readable'

stringer('hello').pipe process.stdout

But nothing logs in the console. What am I doing wrong?

Answer Source

What you need as you say yourself is a readable stream not a transformation stream. Additionally you have a bug because string.split('') always return the same Array and then .shift() will always return the same letter. Your code once rewritten is as follows:

'use strict'

Readable = require('stream').Readable

stringer = (string) ->
  array = string.split('')
  new Readable
    read: (size) ->
      @push array.shift()

readable = stringer('hello')

readable.on 'readable', ->
  console.log 'readable'

readable.pipe process.stdout
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download