Javascript String nodejs流实现

Sam*_*uel 3 javascript node.js

我需要一个nodejs流(http://nodejs.org/api/stream.html)实现,它将数据发送到字符串.你认识的人吗?

为了直接,我正在尝试管理这样的请求响应:request('http://google.com/doodle.png').pipe(fs.createWriteStream('doodle.png'))

来自https://github.com/mikeal/request

谢谢

Mic*_*ley 11

编写符合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);
Run Code Online (Sandbox Code Playgroud)


dan*_*uzz 5

您可能会发现类Sink的在pipette模块适合完成这个用例.使用它你可以写:

var sink = new pipette.Sink(request(...));
sink.on('data', function(buffer) {
  console.log(buffer.toString());
}
Run Code Online (Sandbox Code Playgroud)

Sink还可以合理地优雅地处理从流中返回的错误事件.有关详细信息,请参阅https://github.com/Obvious/pipette#sink.

[编辑:因为我意识到我使用了错误的事件名称.]