日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 前端技术 > HTML >内容正文

HTML

好程序员web前端分享Nodejs学习笔记之Stream模块

發(fā)布時(shí)間:2025/6/17 HTML 107 豆豆
生活随笔 收集整理的這篇文章主要介紹了 好程序员web前端分享Nodejs学习笔记之Stream模块 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

好程序員web前端分享Nodejs學(xué)習(xí)筆記之Stream模塊
  一,開篇分析

  流是一個(gè)抽象接口,被 Node 中的很多對(duì)象所實(shí)現(xiàn)。比如對(duì)一個(gè) HTTP 服務(wù)器的請(qǐng)求是一個(gè)流,stdout 也是一個(gè)流。流是可讀,可寫或兼具兩者的。

  最早接觸Stream是從早期的unix開始的, 數(shù)十年的實(shí)踐證明Stream 思想可以很簡(jiǎn)單的開發(fā)出一些龐大的系統(tǒng)。

  在unix里,Stream是通過 "|" 實(shí)現(xiàn)的。在node中,作為內(nèi)置的stream模塊,很多核心模塊和三方模塊都使用到。

  和unix一樣,node stream主要的操作也是.pipe(),使用者可以使用反壓力機(jī)制來控制讀和寫的平衡。

  Stream 可以為開發(fā)者提供可以重復(fù)使用統(tǒng)一的接口,通過抽象的Stream接口來控制Stream之間的讀寫平衡。

  一個(gè)TCP連接既是可讀流,又是可寫流,而Http連接則不同,一個(gè)http request對(duì)象是可讀流,而http response對(duì)象則是可寫流。

  流的傳輸過程默認(rèn)是以buffer的形式傳輸?shù)?#xff0c;除非你給他設(shè)置其他編碼形式,以下是一個(gè)例子:

  • <p><font size="3">
  • </font></p>
  • <p><font size="3">  var http = require('http') ;</font></p>
  • <p><font size="3">  var server = http.createServer(function(req,res){</font></p>
  • <p><font size="3">  res.writeHeader(200, {'Content-Type': 'text/plain'}) ;</font></p>
  • <p><font size="3">  res.end("Hello,大熊!") ;</font></p>
  • <p><font size="3">  }) ;</font></p>
  • <p><font size="3">  server.listen(8888) ;</font></p>
  • <p><font size="3">  console.log("http server running on port 8888 ...") ;</font></p>

  •   運(yùn)行后會(huì)有亂碼出現(xiàn),原因就是沒有設(shè)置指定的字符集,比如:“utf-8” 。

      修改一下就好:

      var http = require('http') ;

  • <p><font size="3">  var server = http.createServer(function(req,res){</font></p>
  • <p><font size="3">  res.writeHeader(200,{</font></p>
  • <p><font size="3">  'Content-Type' : 'text/plain;charset=utf-8' // 添加charset=utf-8</font></p>
  • <p><font size="3">  }) ;</font></p>
  • <p><font size="3">  res.end("Hello,大熊!") ;</font></p>
  • <p><font size="3">  }) ;</font></p>
  • <p><font size="3">  server.listen(8888) ;</font></p>
  • <p><font size="3">  console.log("http server running on port 8888 ...") ;</font></p>

  •   運(yùn)行結(jié)果:

      為什么使用Stream

      node中的I/O是異步的,因此對(duì)磁盤和網(wǎng)絡(luò)的讀寫需要通過回調(diào)函數(shù)來讀取數(shù)據(jù),下面是一個(gè)文件下載例子

      上代碼:

  • <p><font size="3">  var http = require('http') ;</font></p>
  • <p><font size="3">  var fs = require('fs') ;</font></p>
  • <p><font size="3">  var server = http.createServer(function (req, res) {</font></p>
  • <p><font size="3">  fs.readFile(__dirname + '/data.txt', function (err, data) {</font></p>
  • <p><font size="3">  res.end(data);</font></p>
  • <p><font size="3">  }) ;</font></p>
  • <p><font size="3">  }) ;</font></p>
  • <p><font size="3">  server.listen(8888) ;</font></p>

  •   代碼可以實(shí)現(xiàn)需要的功能,但是服務(wù)在發(fā)送文件數(shù)據(jù)之前需要緩存整個(gè)文件數(shù)據(jù)到內(nèi)存,如果"data.txt"文件很

      大并且并發(fā)量很大的話,會(huì)浪費(fèi)很多內(nèi)存。因?yàn)橛脩粜枰鹊秸麄€(gè)文件緩存到內(nèi)存才能接受的文件數(shù)據(jù),這樣導(dǎo)致

      用戶體驗(yàn)相當(dāng)不好。不過還好(req,res)兩個(gè)參數(shù)都是Stream,這樣我們可以用fs.createReadStream()代替fs.readFile()。如下:

      var http = require('http') ;

  • <p><font size="3">  var fs = require('fs') ;</font></p>
  • <p><font size="3">  var server = http.createServer(function (req, res) {</font></p>
  • <p><font size="3">  var stream = fs.createReadStream(__dirname + '/data.txt') ;</font></p>
  • <p><font size="3">  stream.pipe(res) ;</font></p>
  • <p><font size="3">  }) ;</font></p>
  • <p><font size="3">  server.listen(8888) ;</font></p>

  •   .pipe()方法監(jiān)聽fs.createReadStream()的'data' 和'end'事件,這樣"data.txt"文件就不需要緩存整

      個(gè)文件,當(dāng)客戶端連接完成之后馬上可以發(fā)送一個(gè)數(shù)據(jù)塊到客戶端。使用.pipe()另一個(gè)好處是可以解決當(dāng)客戶

      端延遲非常大時(shí)導(dǎo)致的讀寫不平衡問題。

      有五種基本的Stream:readable,writable,transform,duplex,and "classic” 。(具體使用請(qǐng)自己查閱api)

      二,實(shí)例引入

      當(dāng)內(nèi)存中無法一次裝下需要處理的數(shù)據(jù)時(shí),或者一邊讀取一邊處理更加高效時(shí),我們就需要用到數(shù)據(jù)流。NodeJS中通過各種Stream來提供對(duì)數(shù)據(jù)流的操作。

      以大文件拷貝程序?yàn)槔?#xff0c;我們可以為數(shù)據(jù)源創(chuàng)建一個(gè)只讀數(shù)據(jù)流,示例如下:

      var rs = fs.createReadStream(pathname);

  • <p><font size="3">  rs.on('data', function (chunk) {</font></p>
  • <p><font size="3">  doSomething(chunk) ; // 具體細(xì)節(jié)自己任意發(fā)揮</font></p>
  • <p><font size="3">  });</font></p>
  • <p><font size="3">  rs.on('end', function () {</font></p>
  • <p><font size="3">  cleanUp() ;</font></p>
  • <p><font size="3">  }) ;</font></p>

  •   代碼中data事件會(huì)源源不斷地被觸發(fā),不管doSomething函數(shù)是否處理得過來。代碼可以繼續(xù)做如下改造,以解決這個(gè)問題。

  • <p><font size="3">
  • </font></p>
  • <p><font size="3">  var rs = fs.createReadStream(src) ;</font></p>
  • <p><font size="3">  rs.on('data', function (chunk) {</font></p>
  • <p><font size="3">  rs.pause() ;</font></p>
  • <p><font size="3">  doSomething(chunk, function () {</font></p>
  • <p><font size="3">  rs.resume() ;</font></p>
  • <p><font size="3">  }) ;</font></p>
  • <p><font size="3">  }) ;</font></p>
  • <p><font size="3">  rs.on('end', function () {</font></p>
  • <p><font size="3">  cleanUp();</font></p>
  • <p><font size="3">  }) ;</font></p>

  •   給doSomething函數(shù)加上了回調(diào),因此我們可以在處理數(shù)據(jù)前暫停數(shù)據(jù)讀取,并在處理數(shù)據(jù)后繼續(xù)讀取數(shù)據(jù)。

      此外,我們也可以為數(shù)據(jù)目標(biāo)創(chuàng)建一個(gè)只寫數(shù)據(jù)流,如下:
      var rs = fs.createReadStream(src) ;

  • <p><font size="3">  var ws = fs.createWriteStream(dst) ;</font></p>
  • <p><font size="3">  rs.on('data', function (chunk) {</font></p>
  • <p><font size="3">  ws.write(chunk);</font></p>
  • <p><font size="3">  }) ;</font></p>
  • <p><font size="3">  rs.on('end', function () {</font></p>
  • <p><font size="3">  ws.end();</font></p>
  • <p><font size="3">  }) ;</font></p>

  •   doSomething換成了往只寫數(shù)據(jù)流里寫入數(shù)據(jù)后,以上代碼看起來就像是一個(gè)文件拷貝程序了。但是以上代碼存在上邊提到的問題,如果寫入速度跟不上讀取速度的話,只寫數(shù)據(jù)流內(nèi)部的緩存會(huì)爆倉(cāng)。我們可以根據(jù).write方法的返回值來判斷傳入的數(shù)據(jù)是寫入目標(biāo)了,還是臨時(shí)放在了緩存了,并根據(jù)drain事件來判斷什么時(shí)候只寫數(shù)據(jù)流已經(jīng)將緩存中的數(shù)據(jù)寫入目標(biāo),可以傳入下一個(gè)待寫數(shù)據(jù)了。因此代碼如下:

      var rs = fs.createReadStream(src) ;

  • <p><font size="3">  var ws = fs.createWriteStream(dst) ;</font></p>
  • <p><font size="3">  rs.on('data', function (chunk) {</font></p>
  • <p><font size="3">  if (ws.write(chunk) === false) {</font></p>
  • <p><font size="3">  rs.pause() ;</font></p>
  • <p><font size="3">  }</font></p>
  • <p><font size="3">  }) ;</font></p>
  • <p><font size="3">  rs.on('end', function () {</font></p>
  • <p><font size="3">  ws.end();</font></p>
  • <p><font size="3">  });</font></p>
  • <p><font size="3">  ws.on('drain', function () {</font></p>
  • <p><font size="3">  rs.resume();</font></p>
  • <p><font size="3">  }) ;</font></p>

  •   最終實(shí)現(xiàn)了數(shù)據(jù)從只讀數(shù)據(jù)流到只寫數(shù)據(jù)流的搬運(yùn),并包括了防爆倉(cāng)控制。因?yàn)檫@種使用場(chǎng)景很多,例如上邊的大文件拷貝程序,NodeJS直接提供了.pipe方法來做這件事情,其內(nèi)部實(shí)現(xiàn)方式與上邊的代碼類似。

      下面是一個(gè)更加完整的復(fù)制文件的過程:

      var fs = require('fs'),

  • <p><font size="3">  path = require('path'),</font></p>
  • <p><font size="3">  out = process.stdout;</font></p>
  • <p><font size="3">  var filePath = '/bb/bigbear.mkv';</font></p>
  • <p><font size="3">  var readStream = fs.createReadStream(filePath);</font></p>
  • <p><font size="3">  var writeStream = fs.createWriteStream('file.mkv');</font></p>
  • <p><font size="3">  var stat = fs.statSync(filePath);</font></p>
  • <p><font size="3">  var totalSize = stat.size;</font></p>
  • <p><font size="3">  var passedLength = 0;</font></p>
  • <p><font size="3">  var lastSize = 0;</font></p>
  • <p><font size="3">  var startTime = Date.now();</font></p>
  • <p><font size="3">  readStream.on('data', function(chunk) {</font></p>
  • <p><font size="3">  passedLength += chunk.length;</font></p>
  • <p><font size="3">  if (writeStream.write(chunk) === false) {</font></p>
  • <p><font size="3">  readStream.pause();</font></p>
  • <p><font size="3">  }</font></p>
  • <p><font size="3">  });</font></p>
  • <p><font size="3">  readStream.on('end', function() {</font></p>
  • <p><font size="3">  writeStream.end();</font></p>
  • <p><font size="3">  });</font></p>
  • <p><font size="3">  writeStream.on('drain', function() {</font></p>
  • <p><font size="3">  readStream.resume();</font></p>
  • <p><font size="3">  });</font></p>
  • <p><font size="3">  setTimeout(function show() {</font></p>
  • <p><font size="3">  var percent = Math.ceil((passedLength / totalSize) * 100);</font></p>
  • <p><font size="3">  var size = Math.ceil(passedLength / 1000000);</font></p>
  • <p><font size="3">  var diff = size - lastSize;</font></p>
  • <p><font size="3">  lastSize = size;</font></p>
  • <p><font size="3">  out.clearLine();</font></p>
  • <p><font size="3">  out.cursorTo(0);</font></p>
  • <p><font size="3">  out.write('已完成' + size + 'MB, ' + percent + '%, 速度:' + diff * 2 +?
  • 'MB/s');</font></p>
  • <p><font size="3">  if (passedLength < totalSize) {</font></p>
  • <p><font size="3">  setTimeout(show, 500);</font></p>
  • <p><font size="3">  } else {</font></p>
  • <p><font size="3">  var endTime = Date.now();</font></p>
  • <p><font size="3">  console.log();</font></p>
  • <p><font size="3">  console.log('共用時(shí):' + (endTime - startTime) / 1000 + '秒。');</font></p>
  • <p><font size="3">  }</font></p>
  • <p><font size="3">  }, 500);</font></p>

  •   可以把上面的代碼保存為 "copy.js" 試驗(yàn)一下我們添加了一個(gè)遞歸的 setTimeout (或者直接使用setInterval)來做一個(gè)旁觀者,

      每500ms觀察一次完成進(jìn)度,并把已完成的大小、百分比和復(fù)制速度一并寫到控制臺(tái)上,當(dāng)復(fù)制完成時(shí),計(jì)算總的耗費(fèi)時(shí)間。

      三,總結(jié)一下
      (1),理解Stream概念。
      (2),熟練使用相關(guān)Stream的api
      (3),注意細(xì)節(jié)的把控,比如:大文件的拷貝,采用的使用 “chunk data” 的形式進(jìn)行分片處理。
      ? (4),pipe的使用
      (5),再次強(qiáng)調(diào)一個(gè)概念:一個(gè)TCP連接既是可讀流,又是可寫流,而Http連接則不同,一個(gè)http request對(duì)象是可讀流,而http response對(duì)象則是可寫流。

    轉(zhuǎn)載于:https://www.cnblogs.com/gcghcxy/p/10881154.html

    《新程序員》:云原生和全面數(shù)字化實(shí)踐50位技術(shù)專家共同創(chuàng)作,文字、視頻、音頻交互閱讀

    總結(jié)

    以上是生活随笔為你收集整理的好程序员web前端分享Nodejs学习笔记之Stream模块的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。