9

I have got stream and I need to get stream content into string. I stream from internet using http.get. I also write stream into file, but I don't want to write file and after that open the same file and read from it... So I need to convert stream into string Thanks for all advices...

2
  • You're question is far too vague. So do you want to convert the incoming data to a string, or write it to disk? Some example code would help. Commented Jul 2, 2013 at 8:21
  • 2
    possible duplicate of Writing node.js stream into a string variable Commented May 25, 2015 at 0:06

2 Answers 2

2
var http = require('http');

var string = '';
var request = http.get("http://www.google.cz", function(response) {       
    response.on('data', function(response){
      string += response.toString();

  }); 
    response.on('end', function(string){
      console.log(string);
    });  
  });

This works for sure. I am using it.

Sign up to request clarification or add additional context in comments.

Comments

0

Instead of using the second nested function, try the toString() method on the stream. This can then be piped wherever you want it to go, and you can also write a through() method that can assign it to a variable or use it directly in the one function.

var http = require('http');

var string = '';
var request = http.get('http://www.google.cz', function (err, data){
  if (err) console.log(err);
  string = data.toString();
  //any other code you may want
});
//anything else

One last note--the http.get() method takes two parameters: the url, and a callback. This requires two parameters, and you may have been getting nothing because it was an empty error message.

1 Comment

I think this only works here because http.get returns an extended stream, in general Readable streams do not have a toString method which works this way.

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.