[英]Javascript String nodejs stream implementation
我需要一个nodejs流(http://nodejs.org/api/stream.html)实现,它将数据发送到字符串。 你认识的人吗?
为了直接,我正在尝试管理这样的请求响应:request('http://google.com/doodle.png')。pipe(fs.createWriteStream('doodle.png'))
来自https://github.com/mikeal/request
谢谢
编写符合Stream接口的类并不困难; 这是一个实现非常基础的示例,似乎与您链接的请求模块一起使用:
var stream = require('stream');
var util = require('util');
var request = require('request');
function StringStream() {
stream.Stream.call(this);
this.writable = true;
this.buffer = "";
};
util.inherits(StringStream, stream.Stream);
StringStream.prototype.write = function(data) {
if (data && data.length)
this.buffer += data.toString();
};
StringStream.prototype.end = function(data) {
this.write(data);
this.emit('end');
};
StringStream.prototype.toString = function() {
return this.buffer;
};
var s = new StringStream();
s.on('end', function() {
console.log(this.toString());
});
request('http://google.com').pipe(s);
您可能会发现pipette
模块中的类Sink
对于此用例非常方便。 使用它你可以写:
var sink = new pipette.Sink(request(...));
sink.on('data', function(buffer) {
console.log(buffer.toString());
}
Sink
还可以合理地优雅地处理从流中返回的错误事件。 有关详细信息,请参阅https://github.com/Obvious/pipette#sink 。
[编辑:因为我意识到我使用了错误的事件名称。]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.