要创建自己的可写流,您有三种可能。
创建自己的课程
为此,您需要1)扩展Writable类2)在您自己的构造函数中调用Writable构造函数3)
_write()在流对象的原型中定义一个方法。
这是一个例子:
var stream = require('stream');var util = require('util');function EchoStream () { // step 2 stream.Writable.call(this);};util.inherits(EchoStream, stream.Writable); // step 1EchoStream.prototype._write = function (chunk, encoding, done) { // step 3 console.log(chunk.toString()); done();}var myStream = new EchoStream(); // instanciate your brand new streamprocess.stdin.pipe(myStream);扩展一个空的可写对象
您可以实例化一个空
Writable对象并实现该
_write()方法,而不是定义新的对象类型:
var stream = require('stream');var echoStream = new stream.Writable();echoStream._write = function (chunk, encoding, done) { console.log(chunk.toString()); done();};process.stdin.pipe(echoStream);使用简化的构造函数API
如果您使用的是io.js,则可以使用简化的构造函数API:
var writable = new stream.Writable({ write: function(chunk, encoding, next) { console.log(chunk.toString()); next(); }});在节点4+中使用ES6类
class EchoStream extends stream.Writable { _write(chunk, enc, next) { console.log(chunk.toString()); next(); }}


