Samuel
Samuel

Reputation: 211

Javascript String nodejs stream implementation

I need a nodejs stream (http://nodejs.org/api/stream.html) implementation that sends data to a string. Do you know anyone?

To be direct I'm trying to pipe a request response like this: request('http://google.com/doodle.png').pipe(fs.createWriteStream('doodle.png'))

FROM https://github.com/mikeal/request

Thanks

Upvotes: 3

Views: 2395

Answers (2)

danfuzz
danfuzz

Reputation: 4353

You might find the class Sink in the pipette module to be handy for this use case. Using that you can write:

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

Sink also handles error events coming back from the stream reasonably gracefully. See https://github.com/Obvious/pipette#sink for details.

[Edit: because I realized I used the wrong event name.]

Upvotes: 5

Michelle Tilley
Michelle Tilley

Reputation: 159105

It would not be difficult to write a class that conforms to the Stream interface; here's an example that implements the very basics, and seems to work with the request module you linked:

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

Upvotes: 11

Related Questions