Node.js - How to get stream into string
Asked Answered
M

2

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

Matisse answered 2/7, 2013 at 8:16 Comment(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.Overpay
possible duplicate of Writing node.js stream into a string variableBulgar
T
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.

Thanasi answered 12/7, 2013 at 16:8 Comment(1)
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.Laudatory
C
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.

Cassis answered 3/2, 2016 at 14:37 Comment(0)
T
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.

Thanasi answered 12/7, 2013 at 16:8 Comment(1)
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.Laudatory

© 2022 - 2024 — McMap. All rights reserved.