如何将字符串转换为可读流? [英] How do I turn a String into a Readable Stream?

查看:70
本文介绍了如何将字符串转换为可读流?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将字符串流传输到另一个流:

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?

推荐答案

您所需要的就像是说自己是可读流而不是转换流。此外,您还有一个错误,因为 string.split('')总是返回相同的数组,然后返回 .shift()将始终返回相同的字母。您的代码一旦重写如下:

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

这篇关于如何将字符串转换为可读流?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆