Piping the response to a end file: get response status
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);
Try this:
req.on('response', function( res ) {
console.log(res.status);
});
This event can not be handled
I don't think so in Node (because of some state not exposed before v0.12), but it should work in the browser.
Should work as demonstrated in this test case (on node): https://github.com/visionmedia/superagent/blob/master/test/node/pipe.js#L25
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.
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.