├── LICENCE ├── README.md ├── ReadyStream.js ├── demo ├── demo1.js ├── demo2.js ├── demo3.js ├── in.txt ├── in2.txt └── in3.txt └── package.json /LICENCE: -------------------------------------------------------------------------------- 1 | (The MIT License) 2 | 3 | Copyright (c) 2015 exolution 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining 6 | a copy of this software and associated documentation files (the 7 | 'Software'), to deal in the Software without restriction, including 8 | without limitation the rights to use, copy, modify, merge, publish, 9 | distribute, sublicense, and/or sell copies of the Software, and to 10 | permit persons to whom the Software is furnished to do so, subject to 11 | the following conditions: 12 | 13 | The above copyright notice and this permission notice shall be 14 | included in all copies or substantial portions of the Software. 15 | 16 | THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, 17 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 18 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 19 | IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 20 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, 21 | TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 22 | SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 23 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ReadyStream 2 | 一个简单易用的数据流封装,让你快速运用stream的强大威力。 3 | 4 | ## 什么是流(What is Stream?) 5 | (已经了解stream的可以跳过这一段啰嗦) 6 | 7 | 首先,流是一种关于【数据传输和流动】的抽像。早在unix时代,流的概念就已经深入人心, 8 | 因为流的概念可以很完美的描述数据的输入,加工,输出,并且很好地处理这些环节中遇到的问题。(比如对大尺寸数据的处理,比如对于加工和消费之间不同步的处理) 9 | 所以后来的所有语言几乎都支持基于流的IO操作。Node.js中固然也不例外,Node.js中共包含4种基础流 10 | * Readable 可读流 如读取文件时的FileReadStream 11 | * Writable 可写流 如大家所熟知的HttpResponse 12 | * Duplex 双向流 即可读又可写的流 如网络通信中的socket 13 | * Transform流(又叫through流) 运输流或者说加工流 这个其实才是非常有用的东西。因为在咱们编程的过程中输入流和输出流系统都有提供,咱们最需要实现的就是对数据进行加工的逻辑。gulp的数据处理基本上就是基于这个流 这个流是可读写的,可以形象的描述数据流从它内部流过,便于你对数据进行加工处理。 14 | 15 | `我的ReadyStream就是对这transform流的一种封装` 16 | 17 | ## 为什么要用ReadyStream (Why tree newbie?) 18 | (讨厌吹牛逼的可以跳过这一段广告) 19 | #### ※上手简单 20 | ReadyStream 将整个数据相关的业务流程抽象成 [写入]-[处理加工]-[保存]的模式。让你迅速的体验基于stream开发的快感,并且通过对异步写入的封装,引导让你写出更清晰的程序结构。 21 | #### ※强大的异步写入/流入 22 | ReadyStream对写入操作做了封装,归一化同步写入还是异步写入。写入操作会自动按顺序依次写入,无论是同步的还是异步的(如写入一个文件)。 23 | 也就是说自动帮你管理前一个写入操作完成后才会执行后续的写入操作。而你只需要写同步风格的代码即可。 24 | 25 | #### ※简单好用的加工处理 26 | ReadyStream可以很方便的引流(pipe)到一个数据加工函数里。而且可以根据需要帮你积蓄数据,一次性给你。 27 | (正常情况下,流肯定是写一点给一点,加工函数会调用多次。积蓄是指等所有的写入都完成,一次性给到加工函数里,加工函数只会调用一次。 28 | #### ※完全可以用ReadyStream做一个gulp 29 | 没有噱头,没人关注呀~ 30 | 其实我的ReadyStream也并非是为了让你重复造个gulp轮子的。 31 | 而是更好地在自己的项目中运用流的力量 32 | 33 | # 什么是ReadyStream?(What ghosts?) 34 | (想快速上手使用的可以跳过这段扯淡) 35 | 36 | ReadyStream是一个链式Transform流封装。提供非常方便的流操作。 37 | 诸如`写入文件`,`异步写入数据`,`pipe到加工函数`,`预缓存流数据`等。 38 | ###### 为什么要是链式的? 39 | 正常情况下一个可读流通过readable.pipe(dest) 引流到另外一个stream之后 你想继续pipe就只能在这个另外的流(dest)上pipe。 40 | 而ReadyStream则会保持最后一个dest的引用,每次pipe是在基于这个readystream的dest引用,所以可以针对这一个readystream 实例一路pipe管子接到死,当然也同时保留并联pipe的能力(我这里称之为分流bypass) 41 | ###### 然而链式有什么用呢? 42 | 想来想去其实场景并不多(囧rz),一般用于框架中需要暴露一个单例的stream给用户(开发者)。而这个stream又可能经过一系列的管子进行处理,如果用传统pipe就没办法一直基于这个stream进行处理,你必须像接力一样一路追踪下去。 43 | 在我的MVC框架中,我使用ReadyStream代替了http response,是因为response是个writable只能写数据,而无法pipe进行处理。 44 | 所以我将ReadyStream暴露给用户可以让用户方便的进行数据写入和处理,而且上面也说了,链式让readystream可以以单例的形式存在, 45 | 因此在各个阶段,无论是开发者还是我的框架只需要处理这个统一的readystream实例就够了。例如在经过了业务中间件之后,后续的中间件都可以基于这一个readyStream进行数据加工(如gzip) 46 | 47 | # 如何使用?(How to play?) 48 | 49 | #### 安装 50 | npm install ready-stream 51 | 52 | ##### 创建ReadyStream 53 | ```javascript 54 | 55 | //这样就创建了一个空的ReadyStream 56 | var stream=new ReadyStream(); 57 | //其实ReadyStream接收两个参数,一般用不上。 58 | //而且需要你对stream系统有比较深的了解。如流本身的_transform和ObjectMode等配置 59 | //如有需要请看源码 60 | ``` 61 | ##### 写入数据 62 | 63 | ```javascript 64 | //写入一个文件 65 | stream.writeFile("./in.txt");//文件内容为"hello" 66 | ``` 67 | 68 | 写文件是一种异步的写操作, 69 | 异步的写操作会等之前所有的异步写操作完成之后才会开始写入数据 70 | 所以in2.txt会在in.txt全部写入后才开始写入 71 | ```javascript 72 | stream.writeFile("./in2.txt");//文件内容为" world" 73 | ``` 74 | 75 | 因为readyStream本身也是一个标准的transform流所以也可以用这种方式写入文件 76 | 一样会等前边的异步写入完成之后开始写入 77 | 78 | ```javascript 79 | var input=Fs.createReadStream('./in3.txt');//文件内容为 " readystream\n" 80 | input.pipe(stream);//也可以用stream.inflow(input)性质一样 81 | ``` 82 | ###### 往流中写入数据 83 | put会等待之前所有的异步写入操作完成之后才开始写入, 84 | 如果之前没有异步写操作 则会立即(同步)写入 85 | 所以"hahaha"会等in.txt和 in2.txt都全部写入之后才会写入 86 | 另外 put也可以写入封装好的异步数据 下文会重点介绍 87 | ```javascript 88 | stream.put("hahaha\n"); 89 | 90 | /* 91 | * 同步写入数据 这个是writable的原生方法 只允许写入buffer类型或者string 92 | * 由于是同步写入数据 会在所有异步写入之前写入 93 | * 强烈不推荐这种方式写入,保留它是因为这是一个stream必须的方法。请尽量使用put 94 | */ 95 | stream.write("sync\n"); 96 | ``` 97 | ##### 处理加工数据-串联接水管 98 | ```javascript 99 | stream.pipe(function(chunk,encoding,next){ 100 | //[chunk]:数据块(是一个buffer)[encoding]:数据的编码[next]:执行下一步的回调函数 101 | 102 | /* 103 | * 这个函数就是数据的加工函数(第一个管子) 104 | * 下面buffered参数为false(可以缺省不写)也就是说不积蓄数据,上面对流的每一次write都会调用这个函数 105 | *(writeFile根据文件的大小和设置的读取缓冲大小可能会有多次write) 106 | */ 107 | 108 | //写出数据 把加工好(当然这里是原样写出了,没加工)的数据流出这个管子(传到下一个管子或者传到输出流) 109 | this.push(chunk); 110 | /* 111 | * next 这个非常重要只有执行next才会加工下一个数据块 112 | * 为啥要有next 因为你加工数据的过程可能是个异步的,所以你需要在异步过程完成之后才调用next 113 | */ 114 | next(); 115 | 116 | },false/*buffered*/); 117 | stream.pipe(function(chunk,encoding,next){ 118 | //这个函数就是数据的加工函数(第二个管子) 119 | /* 120 | * 下面的bufferd参数为true 表示积蓄数据,会等前面所有的写入操作完成之后才会执行这个函数 121 | * 重点:只有主动调用stream.end() readyStream才知道所有的写入完成,才会执行这个函数 否则会一直等待 122 | */ 123 | 124 | this.push("before\n");//在原数据之前写出数据 125 | this.push(chunk); 126 | this.push("after\n");//在原数据之后写出数据 127 | next(); 128 | },true/*buffered*/); 129 | 130 | 131 | /* 132 | * 结束流 如果前面还有未执行完的异步写入操作 会等所有异步写入操作都完成后才执行 133 | * end表示你要结束整个流的写入,结束一个流之后就不能再往里面写入数据了 134 | */ 135 | stream.end(); 136 | 137 | // 最终把流接到输出流中 本例是接入到终端输出 把之前的内容显示在屏幕上 138 | stream.pipe(process.stdout); 139 | /*结果: 140 | before 141 | sync 142 | hello world ready stream 143 | hahaha 144 | after 145 | */ 146 | ``` 147 | ##### 并联接水管(我更喜欢称之为分流) 148 | 指定pipe的第三个参数为true打开分流模式,或者直接使用.bypass代替.pipe 149 | 分流模式实际上就是指并联的接水管,下图会详细说明 150 | ![abc](http://77fkpo.com5.z0.glb.clouddn.com/73e5505c8919b92cf9693bfe8854d032.png) 151 | 152 | #### put 异步数据 153 | 这个是我重点设计的地方,也是前面所说的引导开发者写出良好代码结构。(所以扯得多一些,希望多关注这一部分) 154 | 如果你想往流中写入的数据,并不是简单的直接数据,需要一系列的操作来获得的(比如需要请求一个url得到这个数据)。 155 | 那么我建议把这种数据封装成`异步数据`,也就是把这种读取数据的过程抽象成一种数据,把它直接put到流中的。 156 | 为什么要这样呢?因为要`关注点分离`!把这种异步的一系列对readystream的操作单独封装起来,剥离出主要的代码结构。能够避免代码分散到各个的异步回调变得支离破碎。这其实是一种层次上的分离,实际上所谓的`异步数据`封装也是对readystream的操作,只不过我把他们分离到不同的层次中,使得代码结构变得清晰,也几乎能保证,主代码(最外层的代码)完全是同步形式的。 157 | 下面说一下如何创建一个`异步数据` 158 | 首先创建一个能够put的异步数据 需要自己实现WriteRequest接口,其实也就是实现doWrite(readyStream)方法,用来描述你的写入逻辑。 159 | 你只要做一个包含doWrite方法的类就好了,当然我也提供了快速创建这个类的方式ReadyStream.WriteRequest.implement(类定义); 160 | 161 | ```javascript 162 | var HttpData=ReadyStream.WriteRequest.implement({ 163 | //构造函数 164 | constructor:function HttpData(url){ 165 | this.url=url; 166 | }, 167 | resolveRedirectUrl:function(headers){ 168 | //处理重定向的url 篇幅原因这里不写具体实现 请参看demo文件夹下的demo2.js 169 | }, 170 | //实现doWrite方法 171 | doWrite:function(readyStream){ 172 | var urlObj = Url.parse(this.url); 173 | var request = Http.request({ 174 | host:urlObj.hostname, 175 | method : 'get', 176 | path : urlObj.path, 177 | port : urlObj.port || 80 178 | }, function(res) { 179 | res.on('data', function(chunk) { 180 | //请求到数据之后写到readyStream里 181 | //这就是在这个层次的写入 同样支持写入复杂的数据(如writeFile)或者嵌套另外一个[异步数据] 182 | readyStream.put(chunk); 183 | }); 184 | res.on('end', function() { 185 | if(res.statusCode == 200) { 186 | //http数据读完了 187 | //结束当前的数据写入 188 | //由于是异步的所以 不end的话 我就不知道你什么时候结束, 189 | //所以必须在你认为异步结束的时候执行.end 190 | //这也是我所说的一个【异步数据】封装的就是一个完整的对readyStream写入的代码层次, 191 | //在这个层次你当然要在合适的时候告诉我写入完成了 192 | readyStream.end(); 193 | } 194 | else if(res.statusCode==302||res.statusCode==301){ 195 | //处理重定向 196 | var urlObj=self.resolveRedirectUrl(res.headers); 197 | //这就是我说的层次分离,在一个【异步数据】中可以put另外一个异步数据(相当于开辟了一个新的层次) 198 | //整个代码变得更清晰和更优雅有木有!(这个逼给几分^_^) 199 | readyStream.put(new HttpData(urlObj)); 200 | //当然千万别忘了end 201 | readyStream.end(); 202 | } 203 | }); 204 | }); 205 | request.end(); 206 | } 207 | }); 208 | 209 | 210 | ``` 211 | 上面就是一个异步数据的封装,有了他,那么程序的主要代码结构就变得非常清晰了,基本上全是同步代码。 212 | ```javascript 213 | var stream=new ReadyStream(); 214 | stream.put(new HttpData('http://www.jd.com/robots.txt')); 215 | stream.put("end"); 216 | stream.end(); 217 | stream.pipe(process.stdout) 218 | ``` 219 | 220 | 这样把数据源的行为单独封装,使之与程序的主要数据流转逻辑(用对stream的写入、加工、写出来描述)分离开来,是一种比较好的思路,是关注点分离的简单实现,而关注点分离正是一个优秀架构的行为准则。 221 | 否则,如果主要逻辑以源数据读取为主,对于stream的操作就会分散到各种异步回调中,就像下面的例子,同样实现上述功能 222 | 223 | ```javascript 224 | var urlObj = Url.parse('http://www.jd.com/robots.txt'); 225 | Http.request({ 226 | host:urlObj.hostname, 227 | method : 'get', 228 | path : urlObj.path, 229 | port : urlObj.port || 80, 230 | }, function(res) { 231 | var stream=new ReadyStream(); 232 | stream.inflow(res);//等同于res.pipe(stream); 233 | stream.put(res); 234 | //如果这时候还需要请求异步数据呢 好吧继续嵌套 235 | Url.parse('http://www.hitour.cc/robots.txt'); 236 | Http.request({ 237 | host:urlObj.hostname, 238 | method : 'get', 239 | path : urlObj.path, 240 | port : urlObj.port || 80, 241 | }, function(response) { 242 | stream.inflow(response); 243 | stream.pipe(process.stdout); 244 | }).end() 245 | }).end(); 246 | ``` 247 | 请对比一下 哪种更清晰。 248 | 249 | ###### 实例 250 | 到现在说了这么多 可能你还是不知道readyStream有啥用? 251 | 那好吧,我就实现一个简单的gulp功能来说明吧 252 | ```javascript 253 | var ReadyStream=require('../ReadyStream'); 254 | var UglifyJS = require("uglify-js"); 255 | var Fs=require('fs'); 256 | var Path=require('path'); 257 | 258 | //主要功能: 259 | //把当前文件夹下的js合并压缩成一个文件 并同时保存一个未压缩的版本 260 | 261 | 262 | //创建一个延时【异步数据】等待一定时间后才写入数据 (没实际意义只是为了体现异步) 263 | var DelayedData=ReadyStream.WriteRequest.implement({ 264 | constructor:function(data,delay){ 265 | this.data=data; 266 | this.delay=delay; 267 | }, 268 | doWrite:function(readyStream){ 269 | var self=this; 270 | setTimeout(function(){ 271 | readyStream.put(self.data); 272 | readyStream.end();//别忘了end呦 273 | },this.delay); 274 | } 275 | }); 276 | 277 | //目录文件【异步数据】 278 | var DirFile=ReadyStream.WriteRequest.implement({ 279 | constructor:function(path,ext){ 280 | this.path=path; 281 | this.ext='.'+ext;//扩展名过滤 282 | }, 283 | doWrite:function(readyStream){ 284 | var self=this; 285 | Fs.readdir(this.path,function(err,files){ 286 | //遍历当前文件夹 287 | files.forEach(function(file){ 288 | if(Path.extname(file)===self.ext) { 289 | //写入文件 且每个文件开头加上文件名注释 290 | readyStream.put('\n/*========file:' + file + '========*/\n'); 291 | readyStream.writeFile(file); 292 | //等待1000ms后再写入下个文件(并插入等待1秒字样) 293 | readyStream.put(new DelayedData("\n等待1秒",1000)); 294 | } 295 | }); 296 | readyStream.end(); 297 | }); 298 | } 299 | }); 300 | var stream=new ReadyStream(); 301 | stream.put(new DirFile('./','js')); 302 | stream.put('//end'); 303 | //分流写入文件 保存一个未压缩版本 304 | stream.pipe(Fs.createWriteStream("./pack.js")); 305 | stream.pipe(function(chunk,encoding,next){ 306 | //压缩处理 307 | this.push(UglifyJS.minify(chunk.toString(), {fromString: true}).code); 308 | next() 309 | },true); 310 | //分流写入文件,保存压缩版本 311 | stream.pipe(Fs.createWriteStream("./pack.min.js")); 312 | //结束 313 | stream.end(); 314 | ``` 315 | 316 | #### 联系作者 317 | 如果有什么问题和建议,欢迎来吐槽~~ 318 | 吐槽热线:tanhawk#163.com 319 | -------------------------------------------------------------------------------- /ReadyStream.js: -------------------------------------------------------------------------------- 1 | var Transform = require('stream').Transform; 2 | var Readable = require('stream').Readable; 3 | var Writable = require('stream').Writable; 4 | var Util = require('util'); 5 | var Fs = require('fs'); 6 | var rawPipe = Readable.prototype.pipe; 7 | var rawEnd = Writable.prototype.end; 8 | /** 9 | * ReadyStream 10 | * @author exolution 11 | * @version 0.10 12 | * @since 2015 13 | */ 14 | function ReadyStream(config, transform) { 15 | 16 | if(typeof config === 'function') { 17 | this._transform = config; 18 | } 19 | else { 20 | this.config = config || {}; 21 | if(typeof transform === 'function') { 22 | this._transform = transform; 23 | } 24 | } 25 | //it's a transform stream 26 | // 继承于transform类 27 | Transform.call(this, config); 28 | this.writeRequestManager = new WriteRequestManager(this); 29 | //实际上它本身是一系列transform流的链 它内部永远保存最新流经的transform流的引用 30 | //in fact,it's a chain of transform stream.it hold the latest transform stream which data flowed in 31 | this.currentStream = this; 32 | this.on('pipe', function(source) { 33 | this.writeRequestManager.addStream(source); 34 | }); 35 | } 36 | Util.inherits(ReadyStream, Transform); 37 | //implement _transform 38 | ReadyStream.prototype._transform = function(chunk, encoding, next) { 39 | next(null, chunk); 40 | }; 41 | /** 42 | * extended pipe 43 | * you can pipe the stream to a function which as processor of this stream data 44 | * in fact,this function will be encapsulated to a transform stream. 45 | * 46 | * 扩展的pipe 47 | * 引流 48 | * 把当前的数据流引入到一个管子里 这个管子由dest参数指定,管子可以是一个函数 这个函数作为流的加工函数(实际上这个函数会被封装成transform stream) 49 | * buffered参数为true时 会buffer所有的流数据 等流数据写入完成后一次性调用这个加工函数 50 | * 否则 可能会调用多次(流本身就不是一次性写完的) 51 | * bypass代表是否分流 默认为false 意思是正常情况下 每次调用pipe 就会给流接一个管子 这些管子是依次串联的 52 | * 如果bypass =true 这些管子则会并联的接起来。另外如果pipe到一个只可写不可读的单向流 默认分流 53 | */ 54 | ReadyStream.prototype.pipe = function(dest, buffered, bypass) { 55 | if(typeof dest === 'function') { 56 | var transform = new Transform(this.config); 57 | if(this.config.objectMode) buffered = false; 58 | transform._transform = dest; 59 | if(buffered) { 60 | var bufferList = [], encoding; 61 | transform._transform = function(chunk, enc, next) { 62 | bufferList.push(chunk); 63 | encoding = enc; 64 | next(); 65 | }; 66 | transform._flush = function(done) { 67 | dest.call(transform, Buffer.concat(bufferList), encoding, done); 68 | bufferList = null; 69 | } 70 | } 71 | else { 72 | transform._transform = dest; 73 | } 74 | rawPipe.call(this.currentStream, transform); 75 | if(!bypass)this.currentStream = transform; 76 | } 77 | else { 78 | rawPipe.call(this.currentStream, dest); 79 | if(dest.readable && !bypass) { 80 | this.currentStream = dest; 81 | } 82 | } 83 | return this; 84 | }; 85 | /** 86 | * 分流stream 87 | * */ 88 | ReadyStream.prototype.bypass = function(dest, buffered) { 89 | return this.pipe(dest, buffered, true); 90 | }; 91 | /* 92 | * 写入文件数据 这是一个异步的写操作 93 | * 如果多次调用此方法 后续的写操作只有在上一个文件全部写入后才会执行 94 | * */ 95 | ReadyStream.prototype.writeFile = function(path, config, manualEnd) { 96 | this.inflow(Fs.createReadStream(path, config), manualEnd); 97 | }; 98 | /** 99 | * 写入一个流 其实相当于.pipe(readySteam); 100 | * */ 101 | ReadyStream.prototype.inflow = function(readableStream, manualEnd) { 102 | readableStream.pipe(this, manualEnd ? {end : false} : undefined); 103 | }; 104 | /* 105 | * 异步写数据操作 106 | * 异步写操作会等待之前所有的异步写操作完成之后才会写入 107 | * 如果之前没有异步写操作 则会立即(同步)写入数据 108 | * */ 109 | ReadyStream.prototype.put = function(data) { 110 | if(data === null || data === undefined) { 111 | return null; 112 | } 113 | if(typeof data.doWrite === 'function') { 114 | var writeRequest = data; 115 | writeRequest._async=true; 116 | } 117 | else if(data.readable) { 118 | writeRequest = new StreamWriteRequest(data); 119 | } 120 | else { 121 | writeRequest = new DataWriteRequest(data); 122 | } 123 | this.writeRequestManager.addOrRun(writeRequest) 124 | }; 125 | ReadyStream.prototype.end = function(chunk, encoding, cb) { 126 | this.writeRequestManager.end(chunk, encoding, cb); 127 | }; 128 | ReadyStream.prototype.drain = function() { 129 | this.writeRequestManager.drain(); 130 | }; 131 | /** 132 | * 写入请求管理器 133 | * */ 134 | function WriteRequestManager(readyStream) { 135 | this.readyStream = readyStream; 136 | this.stack = [ 137 | { 138 | end:null, 139 | writeRequest:[] 140 | } 141 | ]; 142 | } 143 | WriteRequestManager.prototype.push = function(writeRequest) { 144 | this.stack[this.stack.length - 1].writeRequest.push(writeRequest); 145 | }; 146 | WriteRequestManager.prototype.newContext = function() { 147 | this.stack.push({ 148 | end:null, 149 | writeRequest:[] 150 | }); 151 | }; 152 | WriteRequestManager.prototype.addOrRun = function(writeRequest) { 153 | if(this.isWriting()) { 154 | this.push(writeRequest); 155 | } 156 | else { 157 | this.run(writeRequest, true); 158 | } 159 | }; 160 | WriteRequestManager.prototype.drain = function() { 161 | var context = this.stack[this.stack.length - 1]; 162 | context.writeRequest.shift(); 163 | if(context.writeRequest.length > 0) { 164 | this.run(context.writeRequest[0]); 165 | if(context.writeRequest[0].sync) { 166 | this.drain(); 167 | } 168 | } 169 | 170 | else if(context.end) { 171 | if(this.stack.length > 1){ 172 | this.stack.pop(); 173 | this.drain(); 174 | } 175 | else{ 176 | this.end(context.end.chunk, context.end.encoding, context.end.cb); 177 | } 178 | } 179 | }; 180 | WriteRequestManager.prototype.run = function(writeRequest, immediately) { 181 | var self = this; 182 | if(writeRequest._async) { 183 | if(immediately)this.push(writeRequest); 184 | process.nextTick(function() { 185 | self.newContext(); 186 | writeRequest.doWrite(self.readyStream); 187 | }); 188 | } 189 | else { 190 | writeRequest.doWrite(this.readyStream); 191 | } 192 | }; 193 | WriteRequestManager.prototype.end=function(chunk, encoding, cb){ 194 | if(this.stack.length==1&&!this.isWriting()){ 195 | rawEnd.call(this.readyStream,chunk, encoding, cb); 196 | } 197 | else{ 198 | if(this.currentSourceStream){ 199 | if(this.currentSourceStream._readableState.ended){ 200 | this.currentSourceStream=null; 201 | this.drain(); 202 | } 203 | else{ 204 | this.stack[this.stack.length-1].end = { 205 | chunk : chunk, 206 | encoding : encoding, 207 | cb : cb 208 | }; 209 | } 210 | } 211 | else{ 212 | this.stack[this.stack.length-1].end = { 213 | chunk : chunk, 214 | encoding : encoding, 215 | cb : cb 216 | }; 217 | if(!this.isWriting()){ 218 | this.drain(); 219 | } 220 | } 221 | } 222 | }; 223 | WriteRequestManager.prototype.addStream = function(stream) { 224 | if(this.isWriting()) { 225 | process.nextTick(function() { 226 | stream.pause(); 227 | }) 228 | } 229 | else { 230 | this.currentSourceStream = stream; 231 | } 232 | this.push(new StreamWriteRequest(stream)); 233 | 234 | }; 235 | WriteRequestManager.prototype.isWriting = function() { 236 | return this.stack[this.stack.length - 1].writeRequest.length > 0; 237 | }; 238 | function _serializeData(data) { 239 | if(typeof data == 'object') { 240 | if(!Buffer.isBuffer(data)) { 241 | return JSON.stringify(data); 242 | } 243 | else { 244 | return data; 245 | } 246 | } 247 | else if(data !== undefined && data !== null) { 248 | return data.toString(); 249 | } 250 | else { 251 | return ""; 252 | } 253 | } 254 | function DataWriteRequest(data) { 255 | this.sync = true; 256 | if(data === undefined || data === null) { 257 | return null; 258 | } 259 | this.data = _serializeData(data); 260 | } 261 | DataWriteRequest.prototype.doWrite = function(readyStream) { 262 | readyStream.write(this.data); 263 | }; 264 | function StreamWriteRequest(stream) { 265 | this.stream = stream; 266 | } 267 | StreamWriteRequest.prototype.doWrite = function(readyStream) { 268 | readyStream.writeRequestManager.currentSourceStream = this.stream; 269 | var self = this; 270 | process.nextTick(function() { 271 | self.stream.resume(); 272 | }); 273 | 274 | }; 275 | module.exports = function(config, transform) { 276 | return new ReadyStream(config, transform); 277 | }; 278 | module.exports.WriteRequest={ 279 | implement:function(definition){ 280 | var WriteRequest=definition.hasOwnProperty("constructor")?definition.constructor:function WriteRequest(){}; 281 | WriteRequest.prototype=definition; 282 | return WriteRequest; 283 | } 284 | }; 285 | -------------------------------------------------------------------------------- /demo/demo1.js: -------------------------------------------------------------------------------- 1 | var ReadyStream=require('../ReadyStream'); 2 | var Fs=require('fs'); 3 | 4 | var stream=new ReadyStream(); 5 | //往流中写入一个文件 6 | stream.writeFile("./in.txt");//文件内容为"hello" 7 | //写文件是一种异步的写操作, 8 | //异步的写操作会等之前所有的异步写操作完成之后才会开始写入数据 9 | //所以in2.txt会在in.txt全部写入后才开始写入 10 | stream.writeFile("./in2.txt");//文件内容为" world" 11 | 12 | //因为readyStream本身也是一个标准的transform流所以也可以用这种方式写入文件 13 | //一样会等前边的异步写入完成之后开始写入 14 | var input=Fs.createReadStream('./in3.txt');//文件内容为 " readystream\n" 15 | input.pipe(stream); 16 | //也可以用stream.inflow(input)性质一样 17 | //往流中写入数据 18 | //put会等待之前所有的异步写入操作完成之后才开始写入, 19 | //如果之前没有异步写操作 则会立即(同步)写入 20 | //所以"hahaha"会等in.txt和 in2.txt都全部写入之后才会写入 21 | //另外 put也可以写入异步数据 下文会介绍 22 | stream.put("hahaha\n"); 23 | 24 | //同步写入数据 这个是writable的原生方法 只允许写入buffer类型或者string 25 | //由于是同步写入数据 会在所有异步写入之前写入 26 | //强烈不推荐这种方式写入,保留它是因为这是一个stream必须的方法。请尽量使用put 27 | stream.write("sync\n"); 28 | //处理加工数据-串行接水管 29 | stream.pipe(function(chunk,encoding,next){ 30 | //[chunk]:数据块(是一个buffer)[encoding]:数据的编码[next]:执行下一步的回调函数 31 | //这个函数就是数据的加工函数(第一个管子) 32 | //下面buffered参数为false(可以缺省不写)也就是说不积蓄数据,上面对流的每一次write都会调用这个函数 33 | //(writeFile根据文件的大小和设置的读取缓冲大小可能会有多次write) 34 | this.push(chunk);//写出数据 把加工好(当然这里是原样写出了,没加工)的数据流出这个管子(传到下一个管子或者传到输出流) 35 | next();//next 这个非常重要只有执行next才会加工下一个数据块 为啥要有next 因为你加工数据的过程可能是个异步的,所以你需要在异步过程完成之后才调用next 36 | 37 | },false/*buffered*/); 38 | stream.pipe(function(chunk,encoding,next){ 39 | //这个函数就是数据的加工函数(第二个管子) 40 | //下面的bufferd参数为true 表示积蓄数据,会等前面所有的写入操作完成之后才会执行这个函数 41 | //重点:只有主动调用stream.end() readyStream才知道所有的写入完成,才会执行这个函数 否则会一直等待 42 | this.push("before\n");//在原数据之前写出数据 43 | this.push(chunk); 44 | this.push("after\n");//在原数据之后写出数据 45 | next(); 46 | },true); 47 | //结束流 如果前面还有未执行完的异步写入操作 会等所有异步写入操作都完成后才执行 48 | //结束一个流之后就不能再往里面写入数据了 49 | stream.end(); 50 | // 最终把流接到输出流中 本例是接入到终端输出 把之前的内容显示在屏幕上 51 | stream.pipe(process.stdout); 52 | /*结果: 53 | before 54 | sync 55 | hello world ready stream 56 | hahaha 57 | after 58 | */ 59 | 60 | -------------------------------------------------------------------------------- /demo/demo2.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by godsong on 15-12-18. 3 | */ 4 | 5 | var Http = require('http'); 6 | var Url = require('url'); 7 | var ReadyStream = require('../ReadyStream.js'); 8 | //HttpWriteRequest类 9 | // 名字随意取,其实更建议易懂的名字,比如HttpData。 10 | // 只要包含doWrite方法即可 11 | 12 | var HttpData = ReadyStream.WriteRequest.implement({ 13 | constructor : function HttpData(url) { 14 | if(typeof url === 'object') { 15 | this.urlObj = url; 16 | } 17 | else { 18 | this.urlObj = Url.parse(url); 19 | } 20 | }, 21 | resolveRedirectUrl:function(headers){ 22 | var redirectUrlObj = Url.parse(headers['Location'] || headers['location']); 23 | redirectUrlObj.protocol = redirectUrlObj.protocol || this.urlObj.protocol; 24 | redirectUrlObj.host = redirectUrlObj.host || this.urlObj.host; 25 | redirectUrlObj.hostname = redirectUrlObj.hostname || this.urlObj.hostname; 26 | redirectUrlObj.port = redirectUrlObj.port || this.urlObj.port; 27 | return redirectUrlObj; 28 | }, 29 | doWrite : function(readyStream) { 30 | var self=this; 31 | var request = Http.request({ 32 | host : this.urlObj.hostname, 33 | method : 'get', 34 | path : this.urlObj.path, 35 | port : this.urlObj.port || 80 36 | }, function(res) { 37 | res.on('data', function(chunk) { 38 | //请求到数据之后写到readyStream里 39 | readyStream.put(chunk); 40 | }); 41 | res.on('end', function() { 42 | if(res.statusCode == 200) { 43 | //http数据读完了 44 | //结束当前的数据写入 45 | //由于是异步的所以 不end的话 我就不知道你什么时候结束, 46 | //所以必须在你认为异步结束的时候执行.end 47 | readyStream.end(); 48 | } 49 | else if(res.statusCode == 302 || res.statusCode == 301) { 50 | var urlObj=self.resolveRedirectUrl(res.headers); 51 | readyStream.put(new HttpData(urlObj)); 52 | readyStream.end(); 53 | } 54 | }); 55 | }); 56 | request.end(); 57 | } 58 | }); 59 | //实现doWrite方法 60 | var stream = new ReadyStream(); 61 | stream.put(new HttpData('http://www.jd.com/robots.txt')); 62 | //stream.put(new HttpData('http://localhost:60001/test/redirect')); 63 | stream.writeFile('./in2.txt'); 64 | stream.pipe(process.stdout); 65 | -------------------------------------------------------------------------------- /demo/demo3.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by godsong on 15-12-18. 3 | */ 4 | var ReadyStream=require('../ReadyStream'); 5 | var UglifyJS = require("uglify-js"); 6 | var Fs=require('fs'); 7 | var Path=require('path'); 8 | 9 | //主要功能: 10 | //把当前文件夹下的js合并压缩成一个文件 并同时保存一个未压缩的版本 11 | 12 | var DelayedData=ReadyStream.WriteRequest.implement({ 13 | constructor:function(data,delay){ 14 | this.data=data; 15 | this.delay=delay; 16 | }, 17 | doWrite:function(readyStream){ 18 | var self=this; 19 | setTimeout(function(){ 20 | readyStream.put(self.data); 21 | readyStream.end(); 22 | },this.delay); 23 | } 24 | }); 25 | var DirFile=ReadyStream.WriteRequest.implement({ 26 | constructor:function(path,ext){ 27 | this.path=path; 28 | this.ext='.'+ext; 29 | }, 30 | doWrite:function(readyStream){ 31 | var self=this; 32 | Fs.readdir(this.path,function(err,files){ 33 | //遍历当前文件夹 34 | files.forEach(function(file){ 35 | if(Path.extname(file)===self.ext) { 36 | //写入文件 且每个文件开头加上文件名注释 37 | readyStream.put('\n/*========file:' + file + '========*/\n'); 38 | readyStream.writeFile(file); 39 | readyStream.put(new DelayedData("\n等待1秒",1000)); 40 | } 41 | }); 42 | readyStream.end(); 43 | }); 44 | } 45 | }); 46 | var stream=new ReadyStream(); 47 | stream.put(new DirFile('./','js')); 48 | stream.put('//end'); 49 | //分流写入文件 保存一个未压缩版本 50 | stream.pipe(Fs.createWriteStream("./pack.js")); 51 | stream.pipe(function(chunk,encoding,next){ 52 | //压缩处理 53 | this.push(UglifyJS.minify(chunk.toString(), {fromString: true}).code); 54 | next() 55 | },true); 56 | //分流写入文件,保存压缩版本 57 | stream.pipe(Fs.createWriteStream("./pack.min.js")); 58 | //结束 59 | stream.end(); 60 | -------------------------------------------------------------------------------- /demo/in.txt: -------------------------------------------------------------------------------- 1 | hello -------------------------------------------------------------------------------- /demo/in2.txt: -------------------------------------------------------------------------------- 1 | world -------------------------------------------------------------------------------- /demo/in3.txt: -------------------------------------------------------------------------------- 1 | ready stream 2 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "ready-stream", 3 | "version": "1.0.1", 4 | "main": "ReadyStream.js", 5 | "description": "A Wrapped Transform Stream", 6 | "author": { 7 | "name": "exolution", 8 | "email": "exolution@163.com" 9 | }, 10 | "license": "MIT", 11 | "repository": { 12 | "type": "git", 13 | "url": "git://github.com/exolution/ReadyStream" 14 | }, 15 | "keywords": [ 16 | "stream", 17 | "transform", 18 | "through" 19 | ], 20 | "devDependencies": { 21 | "uglify-js": "^2.6.1" 22 | } 23 | } 24 | --------------------------------------------------------------------------------