如何实现可写流 [英] How to implement a writable stream
问题描述
我想将数据从亚马逊运动流传输到s3日志或Bunyan日志.
I want to pipe data from an amazon kinesis stream to a an s3 log or a bunyan log.
该示例适用于文件写入流或stdout.我将如何伪造自己的可写流?
The sample works with a file write stream or stdout. How would I implmeny my own writable stream?
//this works
var file = fs.createWriteStream('my.log')
kinesisSource.pipe(file)
这表示没有方法开",这是行不通的
this doesn't work saying it has no method 'on'
var stream = {}; //process.stdout works however
stream.writable = true;
stream.write =function(data){
console.log(data);
};
kinesisSource.pipe(stream);
我必须为自己的自定义可写流实现哪些方法,文档似乎表明我需要实现写"而不是上"
what methods do I have to implement for my own custom writable stream, the docs seem to indicate I need to implement 'write' and not 'on'
推荐答案
要创建自己的可写流,您有三种可能.
To create your own writable stream, you have three possibilities.
为此,您需要1)扩展Writable类2)在您自己的构造函数中调用Writable构造函数3)在流对象的原型中定义一个_write()
方法.
For this you'll need 1) to extend the Writable class 2) to call the Writable constructor in your own constructor 3) define a _write()
method in the prototype of your stream object.
这是一个例子:
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);
扩展空的可写对象
您可以实例化一个空的Writable
对象并实现_write()
方法,而不是定义新的对象类型:
Extend an empty Writable object
Instead of defining a new object type, you can instanciate an empty Writable
object and implement the _write()
method:
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();
}
}
这篇关于如何实现可写流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!