Search code examples
stringnode.jsstreamnode.js-stream

Node.js - How to get stream into string


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


Solution

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