您好,登錄后才能下訂單哦!
這篇文章主要介紹“Node.js的Duplex流和Transform流怎么使用”的相關知識,小編通過實際案例向大家展示操作過程,操作方法簡單快捷,實用性強,希望這篇“Node.js的Duplex流和Transform流怎么使用”文章能幫助大家解決問題。
Duplex流一個很好的例子是TCP套接字連接.需要實現_read(size)和_Write(data,encoding,callback)方法.
var stream = require('stream'); var util = require('util'); util.inherits(Duplexer, stream.Duplex); function Duplexer(opt) { stream.Duplex.call(this, opt); this.data = []; } Duplexer.prototype._read = function readItem(size) { var chunk = this.data.shift(); if (chunk == "stop"){ this.push(null); } else{ if(chunk){ this.push(chunk); } } }; Duplexer.prototype._write = function(data, encoding, callback) { this.data.push(data); callback(); }; var d = new Duplexer({allowHalfOpen:true}); d.on('data', function(chunk){ console.log('read: ', chunk.toString()); }); d.on('readable',function(){ console.log("readable"); }) d.on('end', function(){ console.log('Message Complete'); }); d.write("I think, "); d.write("therefore "); d.write("I am."); d.write("Rene Descartes"); d.write("stop");
輸出結果:
"C:\Program Files (x86)\JetBrains\WebStorm 11.0.3\bin\runnerw.exe" F:\nodejs\node.exe stream_duplex.js read: I think, read: therefore read: I am. read: Rene Descartes readable readable readable Message Complete Process finished with exit code 0
Transform變換流擴展了Duplex流,不需要實現而是直接提供。但要實現_transform(chunk,encoding,callback)._flush()這個方法不知道用來做什么的目前
var stream = require("stream"); var util = require("util"); util.inherits(JSONObjectStream, stream.Transform); function JSONObjectStream (opt) { stream.Transform.call(this, opt); }; JSONObjectStream.prototype._transform = function (data, encoding, callback) { object = data ? JSON.parse(data.toString()) : ""; this.emit("object", object); object.handled = true; this.push(JSON.stringify(object)); callback(); }; var tc = new JSONObjectStream(); tc.on("object", function(object){ console.log("Name: %s", object.name); console.log("Color: %s", object.color); }); tc.on("data", function(data){ console.log("Data: %s", data.toString()); }); tc.write('{"name":"Carolinus", "color": "Green"}'); tc.write('{"name":"Solarius", "color": "Blue"}'); tc.write('{"name":"Lo Tae Zhao", "color": "Gold"}'); tc.write('{"name":"Ommadon", "color": "Red"}');
輸出結果:
"C:\Program Files (x86)\JetBrains\WebStorm 11.0.3\bin\runnerw.exe" F:\nodejs\node.exe stream_transform.js Name: Carolinus Color: Green Data: {"name":"Carolinus","color":"Green","handled":true} Name: Solarius Color: Blue Data: {"name":"Solarius","color":"Blue","handled":true} Name: Lo Tae Zhao Color: Gold Data: {"name":"Lo Tae Zhao","color":"Gold","handled":true} Name: Ommadon Color: Red Data: {"name":"Ommadon","color":"Red","handled":true} Process finished with exit code 0
關于“Node.js的Duplex流和Transform流怎么使用”的內容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業相關的知識,可以關注億速云行業資訊頻道,小編每天都會為大家更新不同的知識點。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。