查看“︁Node.js/stream/导流”︁的源代码
来自康健生活
←
Node.js/stream/导流
因为以下原因,您没有权限编辑该页面:
您请求的操作仅限属于该用户组的用户执行:
用户
您可以查看和复制此页面的源代码。
== 示例 == <syntaxhighlight lang="javascript"> 'use strict' import {createReadStream, createWriteStream} from 'fs' createReadStream('/path/to/a/big/file').pipe(createWriteStream('/path/to/the/dest'))</syntaxhighlight> 在网上看到一个很有趣的示例 <syntaxhighlight lang="javascript"> var stream = require('stream') var util = require('util') function ReadStream(){ stream.Readable.call(this) } util.inherits(ReadStream, stream.Readable) ReadStream.prototype._read = function() { this.push('我爱\n') this.push(null) } function WritStream(){ stream.Writable.call(this) } util.inherits(WritStream, stream.Writable) WritStream.prototype._write = function(chunk, encode, cb){ console.log(chunk.toString()) cb() } function TransformStream(){ stream.Transform.call(this) } util.inherits(TransformStream, stream.Transform) TransformStream.prototype._transform = function(chunk, encode, cb){ this.push(chunk) cb() } TransformStream.prototype._flush = function(cb){ this.push('中国') cb() } var rs = new ReadStream() var ws = new WritStream() var ts = new TransformStream() rs.pipe(ts).pipe(ws)</syntaxhighlight> 注意以下几点: # 虽然我们用util.inherits从stream继承了三种流的方法,但是我们依旧需要在三个函数内部使用call(this),原因是,三种流的方法属于stream的私有方法,若不写call,则无法调用三种方法。 # _read 指的是ReadStream的prototype(原型链)的私有部分read # this.push(null), 告诉读入流结束,若不写,则会出现‘我爱’一直循环的现象 # rs.pipe(ts).pipe(ws), transform类似于水管的中间部分,这里建立三种流的实例,先读入,再经过transform的加工,最后读出 # chunk,可以借阅node中buffer的使用方法,其中tostring指的是字符型
返回
Node.js/stream/导流
。
导航菜单
康健生活
搜索
user-page
通知
user-interface-preferences
个人工具
登录
五一
多读书,多运动,多到远处走走,再看看不一样的世界。