superagent icon indicating copy to clipboard operation
superagent copied to clipboard

Piping the response to a end file: get response status

Open hellboy81 opened this issue 12 years ago • 6 comments

How can I get response status if response is piped to file stream?

See code:

var client = supertest(...);
...
// Create writable stream
var writeStream = temp.createWriteStream();
temp.track();

// Superagent request
var req = client.get('/...');

req.on('end', function() {
    // Here we can read file content
    // It can contain actual file content
    // Or JSON string representing error
    // For example {'code': 'F-0001' , 'message': 'File not found'}
    // We should parse this if response code != 200
    // How can we get it here?
    ...
});

// Piping the response to a file
req.pipe(writeStream);

hellboy81 avatar Oct 10 '14 08:10 hellboy81

Try this:

req.on('response', function( res ) {
  console.log(res.status);
});

tjconcept avatar Oct 16 '14 14:10 tjconcept

This event can not be handled

hellboy81 avatar Dec 15 '14 09:12 hellboy81

I don't think so in Node (because of some state not exposed before v0.12), but it should work in the browser.

tjconcept avatar Dec 15 '14 10:12 tjconcept

Should work as demonstrated in this test case (on node): https://github.com/visionmedia/superagent/blob/master/test/node/pipe.js#L25

rase- avatar Mar 03 '15 00:03 rase-

I've tried this and the 'response' callback do not work with get requests.

I'm not sure if this is the 'proper way' to do this, but if you really need it, you can access the response status code in the 'end' callback doing

this.res.statusCode;

This breaks encapsulation, so be aware that it might change in future superagent versions.

juancoen avatar Jun 26 '15 18:06 juancoen

Listen for response and read res.status (or res.statusCode) while piping. This is supported and covered by current pipe tests.

v10.4.0 is available on npm: https://www.npmjs.com/package/superagent/v/10.4.0 GitHub release: https://github.com/forwardemail/superagent/releases/tag/v10.4.0

Consider supporting our efforts to maintain this project by using Forward Email at https://forwardemail.net. We run the only 100% open source and 3rd party audited email service in the world.

titanism avatar Sep 22 '26 16:09 titanism