2016-02-19 74 views
3

我試圖流串到另一個流:如何將字符串轉換爲可讀流?

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 

但沒有記錄在控制檯中。我究竟做錯了什麼?

+0

重複? http://stackoverflow.com/questions/12755997/how-to-create-streams-from-string-in-node-js – Markasoftware

+0

['string-stream']的源代碼(https://github.com/ mikanda/string-stream/blob/master/index.js)可以作爲參考。 – zangw

+0

注意:此問題中的代碼是CoffeeScript,而不是JavaScript。 – mklement0

回答

3

你需要什麼,你說自己是一個可讀的流不是一個轉換流。此外,你有一個錯誤,因爲string.split('')總是返回相同的數組,然後.shift()將始終返回相同的字母。您的代碼重寫如下:

'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 
1

此代碼似乎工作。我不是很熟悉所有的ES6和ES7新的JavaScript語法,你用你的問題是,所以我就重寫了這個從無到有:

const util=require('util'); 
const stream=require('stream'); 

var StringStream=function(strArg){ 
    stream.Readable.call(this); 
    this.str=strArg.split(''); 
} 

util.inherits(StringStream,stream.Readable); 

StringStream.prototype._read=function(numRead){ 
    this.push(this.str.splice(0,numRead).join('')); 
} 

var thisIsAStringStream=new StringStream('this-is-test-text-1234567890'); 
thisIsAStringStream.pipe(process.stdout); 

在我的系統它輸出this-is-test-text-1234567890,所以它是正常工作。這個工程它到底是如何在documentation 建議,通過創建一個擴展使用util.inheritstream.Readable類的類,做stream.Readable.call('this')調用的stream.Readable構造新類的內部構造,並從貫徹_read方法輸出字符該字符串使用this.push

如果它是不明確的,你可以使用這個方法是通過創建使用這樣的數據流:

var helloWorldStream=new StringStream('HelloWorld'); 

然後你可以使用流,就像任何可讀流。

+0

我發現這樣的例子使用繼承,它太破壞了解決方案。是否有使用流的功能方法? 'require('stream')(string).push('hello')。pipe(process.stdout)'? – dopatraman

+0

這實際上是創建自定義可讀流的官方方式。我今天晚些時候可能會看到一些東西,但是。 – Markasoftware

2

如果您的最終目標是將字符串轉換爲可讀流,只需使用模塊into-stream即可。

var intoStream = require('into-stream') 
intoStream('my-str').pipe(process.stdout) 

如果在另一方面,你想知道的方式真正做到這一點你自己,該模塊的源代碼是一個有點鈍,所以我將創建一個例子:

(你實際上並不需要在你的代碼的變換流作爲,只是一個寫流)

var chars = 'my-str'.split('') 
    , Stream = require('stream').Readable 

new Stream({ read: read }).pipe(process.stdout) 

function read(n) { 
    this.push(chars.shift()) 
} 

注意。這隻適用於Node版本> = 4.以前的版本沒有Stream構造函數中的便捷方法。對於年齡較大的節點(0.10.x,0.12.x等)以下稍長示例將工作...

var chars = 'my-str'.split('') 
    , Stream = require('stream').Readable 
    , s = new Stream() 

s._read = function (n) { 
    this.push(chars.shift()) 
} 

s.pipe(process.stdout)