在js代碼中,如果我們讀取數據或者是打印數據,一般是var 或 let 一個變量,再打印出來
但是這樣的方法需要開闢一個新的內存,來保存這個變量
當我們在網頁上讀取內存較大的文件時(比如視頻、圖片等),寫入寫出會極大的佔用內存
這時候就需要在node.js中提供給我們的流——stream
stream可以邊讀邊寫,這樣就可以更好的不佔用太多內存,並且完成所需任務
stream分爲四種:
readable、writable、duplex、transform(這裏各個部分的具體用法可以看stream的詳細文檔)
而pipe的用法也是這裏最常見的
(注意:使用pipe的時候,左側一定是一個流,右側也一定是一個流)
在這裏,我們可以進行一個簡單的流操作
以下是stream.js
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)
運行結果爲
注意以下幾點:
1、雖然我們用util.inherits從stream繼承了三種流的方法,但是我們依舊需要在三個函數內部使用call(this),原因是,三種流的方法屬於stream的私有方法,若不寫call,則無法調用三種方法。
2、_read 指的是ReadStream的prototype(原型鏈)的私有部分read
3、this.push(null), 告訴讀入流結束,若不寫,則會出現‘我愛’一直循環的現象
4、rs.pipe(ts).pipe(ws), transform類似於水管的中間部分,這裏建立三種流的實例,先讀入,再經過transform的加工,最後讀出
5、chunk,可以借閱node中buffer的使用方法,其中tostring指的是字符型