Getting the response status when piping data
Hi,
I need to download data with Node and I'm using superagent to pipe data to a file stream. The example on the documentation works fine for simple cases, but I'm now trying to handle status like 403 or 404.
I understand these are not actual errors so the response body will be piped. I should, however, receive an event that tells me the status so I can abort before I write the data. Unfortunately, the end callbacks are called without the response/error when the request is piped. The callback arguments are always undefined.
Here's the list of handlers I've tried:
superagent
.get('http://httpbin.org/image/png')
.on('response', (response) =>
{
console.log('response', response);
})
.on('error', (error) =>
{
console.log('error', error);
})
.on('end', (error, response) =>
{
console.log('end', error, response);
})
.end(response =>
{
console.log('end', response);
})
.pipe(file);
What's the proper way to get the response status in that case?
Thanks, Warren.
Hi! 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.
Yes, that's what I ended up doing.
However, I don't think I should close this issue because it's a bug IMHO.
I've got the same problem. Handling errors when piping is really cryptic
Now on master the response event should give you this information, and you can call req.abort() in that callback if needed.
I believe this is addressed in the v2.0.0 release as per the comment above. Closing.
Is this still the suggested way to handle errors when downloading/streaming to file?
I get request.abort is not a function running this.
var stream = fs.createWriteStream('path/to/file')
var request = superagent
.get('http://httpbin.org/image/png')
.on('response', function(response) {
if (response.status !== 200) {
request.abort();
}
})
.pipe(stream);
.pipe() does not return a superagent request. Save the superagent reference before calling .pipe().
@kornelski I don't quite fully understand.
What exactly means aborting a request? What do I get? Do I get anything?
Documentation only shows
Aborting requests
To abort requests simply invoke the req.abort() method.
You get the abort event, and no more. It stops downloading further data.