Node.js/stream/导流:修订间差异

来自康健生活
Kangkk​(留言 | 贡献)
创建页面,内容为“== 示例 == <syntaxhighlight lang="javascript"> 'use strict' import {createReadStream, createWriteStream} from 'fs' createReadStream('/path/to/a/big/file').pipe(cre…”
 
Kangkk​(留言 | 贡献)
 
第4行: 第4行:
import {createReadStream, createWriteStream} from 'fs'
import {createReadStream, createWriteStream} from 'fs'
createReadStream('/path/to/a/big/file').pipe(createWriteStream('/path/to/the/dest'))</syntaxhighlight>
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指的是字符型