前言
前幾天別人請(qǐng)教我關(guān)于pipe的問(wèn)題,我發(fā)現(xiàn)我雖然用了nodejs很久,但是由于每次用的不多所以經(jīng)常回避stream的使用,導(dǎo)致一直不熟,現(xiàn)在重新學(xué)習(xí)整理一下相關(guān)知識(shí)。
通過(guò)nodeschool學(xué)習(xí)stream
nodeschool有一個(gè)stream-adventure教程教導(dǎo)stream的使用,很簡(jiǎn)單
簡(jiǎn)單stream進(jìn)行pipe
首先,我們可以通過(guò)管道將輸入定位到輸出,輸入輸出可以是控制臺(tái)或者文件流或者h(yuǎn)ttp請(qǐng)求,比如
process.stdin.pipe(process.stdout) process.stdin.pipe(fs.createWriteStream(path)) fs.createReadStream(path).pipe(process.stdin)
pipe中間進(jìn)行處理
如果我們想要在管道中間進(jìn)行處理,比如想將輸入的字符串變成大寫(xiě)寫(xiě)到輸出里,我們可以使用一些可以作為中間處理的框架,比如through2就很方便
var through2 = require('through2'); var stream = through2(write,end) process.stdin .pipe(stream) .pipe(process.stdout); function write(line,_,next){ this.push(line.toString().toUpperCase()) next(); }) function end(done){ done(); })
stream轉(zhuǎn)化成普通回調(diào)
當(dāng)我們輸入是流,而輸出是個(gè)普通函數(shù),我們需要把輸入流轉(zhuǎn)化為普通的buffer,這時(shí)可以試用concat-stream庫(kù)
var concat = require('concat-stream'); var reverseStream=concat(function(text){ console.log(text.toString().split("").reverse().join("")); }) process.stdin.pipe(reverseStream)
http server中的流
類似stdin和fs,http由于其特性也適合使用流,所以其自帶類似特性
var http = require('http'); var server = http.createServer(function(req,res){ req.pipe(res); })
既作為輸入也作為輸出的流
request框架實(shí)現(xiàn)了如下功能,將一個(gè)流pipe到request請(qǐng)求中,然后將流的內(nèi)容發(fā)給服務(wù)器,然后返回作為流供其他代碼使用,實(shí)現(xiàn)如下
var request = require('request'); var r = request.post('http://localhost:8099'); process.stdin.pipe(r).pipe(process.stdout)
分支管道
下邊是一個(gè)例子,這個(gè)例子將輸入管道中html包含loud class的元素放入另一個(gè)管道進(jìn)行大寫(xiě)操作,然后最后合并成輸出
var trumpet = require('trumpet'); var through2 = require('through2'); var fs = require('fs'); var tr = trumpet(); var stream = tr.select('.loud').createStream(); var upper = through2(function(buf,_,next){ this.push(buf.toString().toUpperCase()); next(); }) stream.pipe(upper).pipe(stream); process.stdin.pipe(tr).pipe(process.stdout);
合并輸入輸出stream例子
合并后的輸入輸出可像前文request一樣使用,下邊這個(gè)例子實(shí)現(xiàn)了使用流的方式進(jìn)行子進(jìn)程調(diào)用
var spawn = require('child_process').spawn; var duplexer2 = require('duplexer2'); module.exports = function(cmd, args){ var c = spawn(cmd,args) return duplexer2(c.stdin,c.stdout) }
總結(jié)
通過(guò)上邊的例子,可以知道stream應(yīng)該還有如何合并等更復(fù)雜的應(yīng)用方式。總之整體上符合如下特性:
聲明:本網(wǎng)頁(yè)內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問(wèn)題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com