Node.js – 如何获取stream到string

我有stream,我需要将stream内容转换为string。 我使用http.get从Internetstream式传输。 我也写stream到文件,但我不想写文件,然后打开同一个文件,并从它读取…所以我需要转换成string的stream感谢所有的build议…

而不是使用第二个嵌套函数,请尝试stream上的toString()方法。 然后可以将它传送到任何你想要的地方,你也可以编写一个可以将它分配给一个variables的通过方法,或者直接在一个函数中使用它。

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 

最后一个注释 – http.get()方法有两个参数:url和一个callback。 这需要两个参数,你可能一直没有得到,因为它是一个空的错误信息。

所以,

 I have this: var centent = ''; var adress = "http://www.google.cz"; var request = http.get(adress.trim(), function(response) { //I need to get content of http stream into variable content and after that continue } 

我在想,这会起作用,但事实并非如此

  var http = require('http'); var string = ''; var request = http.get("http://www.google.cz", function(response) { response.on('data', function(response){ string += response; }); response.on('end', function(string){ console.log(string); }); }); 
 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); }); }); 

这是肯定的。 我正在使用它。