dopatraman dopatraman - 3 months ago 9
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()
done()

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

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()
      return

readable = stringer('hello')

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

readable.pipe process.stdout