11慕課網《進擊Node.js基礎(一)》Buffer和Stream

Buffer

用來保存原始數據html

(logo.png)npm

如下代碼讀取logo.png爲buffer類型
而後將buffer轉化爲string,新建png
能夠將字符串配置: data:image/png;Base64,Buffer.toString()數組

var fs = require('fs')

fs.readFile('logo.png',function(err,origin_buffer){
    console.log('origin_buffer是否Buffer格式:'+Buffer.isBuffer(origin_buffer))
    //console.log('讀取到origin_buffer:' + origin_buffer)
    //建立文件
    fs.writeFile('log_buffer.png',origin_buffer,function(err){
        if(err) console.log(err)
    })

    //var base84Image = new Buffer(origin_buffer).toString('base64')
    //轉爲字符串
    var base64Image = origin_buffer.toString('base64')

    console.log('字符串base64Image:' + base64Image)

    var decodedImage = new Buffer(base64Image, 'base64')

    //console.log('編碼decodedImage:'+decodedImage)
    //console.log('比較origin_buffer和decodedImage:' + Buffer.compare(origin_buffer,decodedImage))

    fs.writeFile('logo_decoded.png',decodedImage,function(err){
        if(err) console.log(err)
    })

})

Stream

暫存和移動數據網絡

經過stream直接copy圖片

var fs  =  require('fs')
var source = fs.readFileSync('../buffer/logo.png')

fs.writeFileSync('stream_copy.png',source)

stream讀操做觸發事件

stream的讀取會觸發事件,經過監聽能夠實現許多功能
stream事件每次傳輸 64kbui

var fs = require('fs')

var readStream = fs.createReadStream('xpg.mp3')
var n=0

//數據傳遞過程當中觸發,監聽data事件
readStream
 .on('data', function(chunk){
    n++
    console.log('data emits')
    console.log('是否以Buffer格式傳遞?:'+Buffer.isBuffer(chunk))
    //console.log(chunk.toString('utf8'))
    //
    readStream.pause()//暫停
    console.log('data pause')
    setTimeout(function(){
        console.log('data pause end')
        readStream.resume()//從新啓動
    },10)
 })
 .on('readable',function(){
    //文件可讀
    console.log('data readable')
 })
 .on('end', function(){
    console.log(n)
    //數據傳遞事件,同時觸發目標不可寫
    console.log('data end')
 })
 .on('close',function(){
    //整個stream關閉結束
    console.log('data close')
 })
 .on('error',function(e){
    console.log('data read error'+e)
 })

stream的讀寫

//文件copy
var fs = require('fs')

var readStream = fs.createReadStream('xpg.mp3')

var writeStream = fs.createWriteStream('copy-xpg.mp3')


readStream.on('data',function(chunk){
    //數據還在緩衝區,未寫完
    if(writeStream.write(chunk) === false){
        console.log('still cached')
        //暫停讀入,防止緩衝區爆掉
        readStream.pause()
    }

})


readStream.on('end',function(){
    writeStream.end()
})

//drain方法,數據被消費完,所有寫入目標
writeStream.on('drain', function(){
    console.log('data drain')

    //從新啓動讀操做
    readStream.resume()
})

Stream種類

  • Readable 可讀流,讀取外部數據,將數據緩衝到內部的buffer數組
  • Writeable 可寫流,消費buffer數組中的數據,寫目標
  • Duplex 雙工流
  • Transform 轉換、雙工

使用pipe

var http = require('http')
var fs = require('fs')
//須要安裝 npm install request
var request = require('request')

http
  .createServer(function(req,res){
    //通俗的作法
    // fs.readFile('../buffer/logo.png', function(err,data){
    //  if(err){
    //      res.end('file not exist!')
    //  }else{
    //      res.writeHeader(200,{'Context-Type':'text/html'})
    //      res.end(data)
    //  }
    // })
    
    //簡潔的方案
    //fs.createReadStream('../buffer/logo.png').pipe(res)
    
    //爬取網絡中的圖片
    request('http://img2.mukewang.com/szimg/5a67ebf50001b6d005400300-228-128.jpg')
      .pipe(res)

  })
  .listen(8090)

  console.log('run on 8090')

使用pipe重寫stream的直接讀寫

var fs = require('fs')

fs.createReadStream('xpg.mp3').pipe(fs.createWriteStream('xpg-pipe.mp3'))

pipe鏈接Readable和Writabel

//文件copy
var fs = require('fs')

var readStream = fs.createReadStream('xpg.mp3')

var writeStream = fs.createWriteStream('copy-xpg.mp3')


readStream.on('data',function(chunk){
    //數據還在緩衝區,未寫完
    if(writeStream.write(chunk) === false){
        console.log('still cached')
        //暫停讀入,防止緩衝區爆掉
        readStream.pause()
    }

})


readStream.on('end',function(){
    writeStream.end()
})

//drain方法,數據被消費完,所有寫入目標
writeStream.on('drain', function(){
    console.log('data drain')

    //從新啓動讀操做
    readStream.resume()
})

本身定製的Readable Write

var stream = require('stream')
var util = require('util')


//定製可讀流
function ReadStream(){
    stream.Readable.call(this)
}
//使ReadStream 繼承stream.Readable的原型
util.inherits(ReadStream,stream.Readable)

ReadStream.prototype._read = function(){
    this.push('I')
    this.push('Love')
    this.push('You')
    //null結束
    this.push(null)
}
//===定製可寫流 
function WriteStream(){
    stream.Writable.call(this)
    this._cached = new Buffer('')
}

util.inherits(WriteStream,stream.Writable)

WriteStream.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('OK')
    cb()
}


var rs = new ReadStream()
var ws = new WriteStream()
var ts = new TransformStream()

rs.pipe(ts).pipe(ws)

相關文章
相關標籤/搜索