淺談Node.js:理解stream
Stream在node.js中是一個抽象的接口,基於EventEmitter,也是一種Buffer的高階封裝,用來處理流資料。流模組便是提供各種API讓我們可以很簡單的使用Stream。
流分為四種類型,如下所示:
Readable,可讀流
Writable,可寫流
Duplex,讀寫流
Transform,擴展的Duplex,可修改寫入的數據,可修改寫入的數據
1、Readable可讀流透過stream.Readable可建立一個可讀流,它有兩種模式:暫停和流動。const fs = require('fs'); const rs = fs.createReadStream('./appbak.js'); var chunkArr = [], chunkLen = 0; rs.on('data',(chunk)=>{ chunkArr.push(chunk); chunkLen+=chunk.length; }); rs.on('end',(chunk)=>{ console.log(Buffer.concat(chunkArr,chunkLen).toString()); });
const rs = fs.createReadStream('./appbak.js'); var chunkArr = [], chunkLen = 0; rs.on('readable',()=>{ var chunk = null; //这里需要判断是否到了流的末尾 if((chunk = rs.read()) !== null){ chunkArr.push(chunk); chunkLen+=chunk.length; } }); rs.on('end',(chunk)=>{ console.log(Buffer.concat(chunkArr,chunkLen).toString()); });
const rs = fs.createReadStream('./下载.png'); rs.on('data',(chunk)=>{ console.log(`接收到${chunk.length}字节数据...`); rs.pause(); console.log(`数据接收将暂停1.5秒.`); setTimeout(()=>{ rs.resume(); },1000); }); rs.on('end',(chunk)=>{ console.log(`数据接收完毕`); });
const rs = fs.createReadStream('./app.js'); rs.pipe(process.stdout);
const ws = fs.createWriteStream('./test.txt'); ws.write('nihao','utf8',()=>{process.stdout.write('this chunk is flushed.');}); ws.end('done.')
function copy(src,dest){ src = path.resolve(src); dest = path.resolve(dest); const rs = fs.createReadStream(src); const ws = fs.createWriteStream(dest); console.log('正在复制中...'); const stime = +new Date(); rs.on('data',(chunk)=>{ if(null === ws.write(chunk)){ rs.pause(); } }); ws.on('drain',()=>{ rs.resume(); }); rs.on('end',()=>{ const etime = +new Date(); console.log(`已完成,用时:${(etime-stime)/1000}秒`); ws.end(); }); function calcProgress(){ } } copy('./CSS权威指南 第3版.pdf','./javascript.pdf');
const ws = fs.createWriteStream('./alphabet.txt'); const alphabetStr = 'abcdefghijklmnopqrstuvwxyz'; ws.on('finish',()=>{ console.log('done.'); }); for(let letter of alphabetStr.split()){ ws.write(letter); } ws.end();//必须调用
Duplex流的扩展,区别在于,Transform流自动将写入端的数据变换后添加到可读端。例如:'zlib streams'、'crypto streams'等都是Transform流。
5、四种流的实现
stream模块提供的API可以让我们很简单的实现流,该模块使用require('stream')引用,我们只要继承四种流中的一个基类(stream.Writable, stream.Readable, stream.Duplex, or stream.Transform),然后实现它的接口就可以了,需要实现的接口如下所示:
| Use-case | Class | Method(s) to implement |
| ------------- |-------------| -----|
| Reading only | Readable | _read |
| Writing only | Writable | _write, _writev |
| Reading and writing | Duplex | _read, _write, _writev |
| Operate on written data, then read the result | Transform | _transform, _flush |
Readable流实现
如上所示,我们只要继承Readable类并实现_read接口即可,,如下所示:
const Readable = require('stream').Readable; const util = require('util'); const alphabetArr = 'abcdefghijklmnopqrstuvwxyz'.split(); /*function AbReadable(){ if(!this instanceof AbReadable){ return new AbReadable(); } Readable.call(this); } util.inherits(AbReadable,Readable); AbReadable.prototype._read = function(){ if(!alphabetArr.length){ this.push(null); }else{ this.push(alphabetArr.shift()); } }; const abReadable = new AbReadable(); abReadable.pipe(process.stdout);*/ /*class AbReadable extends Readable{ constructor(){ super(); } _read(){ if(!alphabetArr.length){ this.push(null); }else{ this.push(alphabetArr.shift()); } } } const abReadable = new AbReadable(); abReadable.pipe(process.stdout);*/ /*const abReadable = new Readable({ read(){ if(!alphabetArr.length){ this.push(null); }else{ this.push(alphabetArr.shift()); } } }); abReadable.pipe(process.stdout);*/ const abReadable = Readable(); abReadable._read = function(){ if (!alphabetArr.length) { this.push(null); } else { this.push(alphabetArr.shift()); } } abReadable.pipe(process.stdout);
以上代码使用了四种方法创建一个Readable可读流,必须实现_read()方法,以及用到了readable.push()方法,该方法的作用是将指定的数据添加到读取队列。
Writable流实现
我们只要继承Writable类并实现_write或_writev接口,如下所示(只使用两种方法):
/*class MyWritable extends Writable{ constructor(){ super(); } _write(chunk,encoding,callback){ process.stdout.write(chunk); callback(); } } const myWritable = new MyWritable();*/ const myWritable = new Writable({ write(chunk,encoding,callback){ process.stdout.write(chunk); callback(); } }); myWritable.on('finish',()=>{ process.stdout.write('done'); }) myWritable.write('a'); myWritable.write('b'); myWritable.write('c'); myWritable.end();
Duplex流实现
实现Duplex流,需要继承Duplex类,并实现_read和_write接口,如下所示:
class MyDuplex extends Duplex{ constructor(){ super(); this.source = []; } _read(){ if (!this.source.length) { this.push(null); } else { this.push(this.source.shift()); } } _write(chunk,encoding,cb){ this.source.push(chunk); cb(); } } const myDuplex = new MyDuplex(); myDuplex.on('finish',()=>{ process.stdout.write('write done.') }); myDuplex.on('end',()=>{ process.stdout.write('read done.') }); myDuplex.write('\na\n'); myDuplex.write('c\n'); myDuplex.end('b\n'); myDuplex.pipe(process.stdout);
上面的代码实现了_read()方法,可作为可读流来使用,同时实现了_write()方法,又可作为可写流来使用。
Transform流实现
实现Transform流,需要继承Transform类,并实现_transform接口,如下所示:
class MyTransform extends Transform{ constructor(){ super(); } _transform(chunk, encoding, callback){ chunk = (chunk+'').toUpperCase(); callback(null,chunk); } } const myTransform = new MyTransform(); myTransform.write('hello world!'); myTransform.end(); myTransform.pipe(process.stdout);
上面代码中的_transform()方法,其第一个参数,要么为error,要么为null,第二个参数将被自动转发给readable.push()方法,因此该方法也可以使用如下写法:
_transform(chunk, encoding, callback){ chunk = (chunk+'').toUpperCase() this.push(chunk) callback(); }
Object Mode流实现
我们知道流中的数据默认都是Buffer类型,可读流的数据进入流中便被转换成buffer,然后被消耗,可写流写入数据时,底层调用也将其转化为buffer。但将构造函数的objectMode选择设置为true,便可产生原样的数据,如下所示:
const rs = Readable(); rs.push('a'); rs.push('b'); rs.push(null); rs.on('data',(chunk)=>{console.log(chunk);});//<Buffer 61>与<Buffer 62> const rs1 = Readable({objectMode:!0}); rs1.push('a'); rs1.push('b'); rs1.push(null); rs1.on('data',(chunk)=>{console.log(chunk);});//a与b
下面利用Transform流实现一个简单的CSS压缩工具,如下所示:
function minify(src,dest){ const transform = new Transform({ transform(chunk,encoding,cb){ cb(null,(chunk.toString()).replace(/[\s\r\n\t]/g,'')); } }); fs.createReadStream(src,{encoding:'utf8'}).pipe(transform).pipe(fs.createWriteStream(dest)); } minify('./reset.css','./reset.min.css');
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持PHP中文网。
更多浅谈Node.js:理解stream相关文章请关注PHP中文网!

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

不同JavaScript引擎在解析和執行JavaScript代碼時,效果會有所不同,因為每個引擎的實現原理和優化策略各有差異。 1.詞法分析:將源碼轉換為詞法單元。 2.語法分析:生成抽象語法樹。 3.優化和編譯:通過JIT編譯器生成機器碼。 4.執行:運行機器碼。 V8引擎通過即時編譯和隱藏類優化,SpiderMonkey使用類型推斷系統,導致在相同代碼上的性能表現不同。

Python更適合初學者,學習曲線平緩,語法簡潔;JavaScript適合前端開發,學習曲線較陡,語法靈活。 1.Python語法直觀,適用於數據科學和後端開發。 2.JavaScript靈活,廣泛用於前端和服務器端編程。

從C/C 轉向JavaScript需要適應動態類型、垃圾回收和異步編程等特點。 1)C/C 是靜態類型語言,需手動管理內存,而JavaScript是動態類型,垃圾回收自動處理。 2)C/C 需編譯成機器碼,JavaScript則為解釋型語言。 3)JavaScript引入閉包、原型鍊和Promise等概念,增強了靈活性和異步編程能力。

JavaScript在Web開發中的主要用途包括客戶端交互、表單驗證和異步通信。 1)通過DOM操作實現動態內容更新和用戶交互;2)在用戶提交數據前進行客戶端驗證,提高用戶體驗;3)通過AJAX技術實現與服務器的無刷新通信。

JavaScript在現實世界中的應用包括前端和後端開發。 1)通過構建TODO列表應用展示前端應用,涉及DOM操作和事件處理。 2)通過Node.js和Express構建RESTfulAPI展示後端應用。

理解JavaScript引擎內部工作原理對開發者重要,因為它能幫助編寫更高效的代碼並理解性能瓶頸和優化策略。 1)引擎的工作流程包括解析、編譯和執行三個階段;2)執行過程中,引擎會進行動態優化,如內聯緩存和隱藏類;3)最佳實踐包括避免全局變量、優化循環、使用const和let,以及避免過度使用閉包。

Python和JavaScript在社區、庫和資源方面的對比各有優劣。 1)Python社區友好,適合初學者,但前端開發資源不如JavaScript豐富。 2)Python在數據科學和機器學習庫方面強大,JavaScript則在前端開發庫和框架上更勝一籌。 3)兩者的學習資源都豐富,但Python適合從官方文檔開始,JavaScript則以MDNWebDocs為佳。選擇應基於項目需求和個人興趣。

Python和JavaScript在開發環境上的選擇都很重要。 1)Python的開發環境包括PyCharm、JupyterNotebook和Anaconda,適合數據科學和快速原型開發。 2)JavaScript的開發環境包括Node.js、VSCode和Webpack,適用於前端和後端開發。根據項目需求選擇合適的工具可以提高開發效率和項目成功率。
