3

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

2 Answers 2

11

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);
Sign up to request clarification or add additional context in comments.

Comments

5

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.]

1 Comment

+1 for the pipette. I like using it. (my dog doesn't, though)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.