Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS Request: How to get the response as a string?

I'm kind of lost. Is it possible to get the response body as a string in .on(response) (see below)? Or am I crazy? I know I can .pipe the response to a WriteStream, but I need both the response body and the response statusCode at the same place in order to continue my code. Thanks!

var request = require("request");
request(url)
.on('response', function(response) {
    console.log(response.statusCode); // 200
    console.log(/* I need to get response body string here */); // <--- can I have the response body as a string here?
})
.on("error", function(err){
    console.log("Problem reaching URL: ", err);
});
like image 264
Emilio Avatar asked Jan 30 '23 12:01

Emilio


1 Answers

I would make in a comment, but I can't.

As in the npm page (considering you don't need pipe), you can have the body along with the response in: :

var request = require("request");

request(url, function (error, response, body) {
  console.log('error:', error); 
  console.log('statusCode:', response && response.statusCode); 
  console.log('body:', body); 
}); 
like image 153
dpetrini Avatar answered Feb 02 '23 04:02

dpetrini