要创建自己的可写流,有三种可能性.
Create your own class
为此,您需要1)扩展可写类2)在自己的构造函数中调用可写构造函数3)在流对象的原型中定义一个_write()
方法.
下面是一个例子:
var stream = require('stream');
var util = require('util');
function EchoStream () { // step 2
stream.Writable.call(this);
};
util.inherits(EchoStream, stream.Writable); // step 1
EchoStream.prototype._write = function (chunk, encoding, done) { // step 3
console.log(chunk.toString());
done();
}
var myStream = new EchoStream(); // instanciate your brand new stream
process.stdin.pipe(myStream);
Extend an empty Writable object
您可以实例化一个空的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);
Use the Simplified Constructor API
如果你使用io.js,你可以使用simplified constructor API:
var writable = new stream.Writable({
write: function(chunk, encoding, next) {
console.log(chunk.toString());
next();
}
});
Use an ES6 class in Node 4+
class EchoStream extends stream.Writable {
_write(chunk, enc, next) {
console.log(chunk.toString());
next();
}
}