如何实现一个可写的stream

我想将数据从亚马逊kinesisstream传输到s3日志或bunyan日志。

该示例使用文件写入stream或标准输出。 我将如何暗示自己的可写入stream?

//this works var file = fs.createWriteStream('my.log') kinesisSource.pipe(file) 

这不起作用,说它没有方法'上'

 var stream = {}; //process.stdout works however stream.writable = true; stream.write =function(data){ console.log(data); }; kinesisSource.pipe(stream); 

我有什么方法来实现我自己的自定义可写stream,文档似乎表明我需要实现'写'而不是'开'

要创build自己的可写stream,您有三种可能性。

创build你自己的class级

为此,您需要1)扩展Writable类2)在您自己的构造函数中调用Writable构造函数3)在stream对象的原型中定义_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); 

扩展一个空的Writable对象

您可以实例化一个空的Writable对象并实现_write()方法,而不是定义一个新的对象types:

 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(); } } 

其实创build一个可写入的stream是相当简单的。 这是一个例子:

 var fs = require('fs'); var Stream = require('stream'); var ws = new Stream; ws.writable = true; ws.bytes = 0; ws.write = function(buf) { ws.bytes += buf.length; } ws.end = function(buf) { if(arguments.length) ws.write(buf); ws.writable = false; console.log('bytes length: ' + ws.bytes); } fs.createReadStream('file path').pipe(ws); 

另外,如果你想创build自己的类,@Paul给出一个很好的答案。