Skip to content Skip to sidebar Skip to footer

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 t

Solution 1:

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

Solution 2:

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


Post a Comment for "Javascript String Nodejs Stream Implementation"