I'm using pkgcloud to build a webservice (express based) that will manage my openstack storage. I have a problem with downloading a file.
the pkgcloud api for download is a bit wierd: it passes to the callback the error and file's metadata, and returns from the function a readable stream with the file's content:
client.download({
container: 'my-container',
remote: 'my-file'
}, function(err, result) {
// handle the download result
})).pipe(myFile);
The problem I have with this is- how can I get the error, the metadata and the stream together? I need the metadata in order to set the content type for my result and obviously I need the error to know if all went well (in case the file doesn't exist, the stream is still returned- just containing an html error message, so I can't count on that for error).
I tried calling it like this:
router.get("/download", function (res, req) {
var stream = client.download(options, function (err, file) {
if (err) {
return res.status(err.status).json({'message' : 'Error downloading file from storage: ' + err.details});
}
}
// I'd like to get the callback's err and file here somehow
stream.pipe(res);
});
but the problem is that the data is piped to res before callback is called, so the callback doesn't help- it is either giving me the error too late, or not giving me the metadata. I also tried moving the stream.pipe(res) into the callback, but it does not work, cause inside the callback I can't access the result stream.
I thought of using promise for that, but how can I tell the promise to 'wait' for both the callback and the returned value? I'm trying to wrap the download function with a function that will run the download with one promise in the callback and one on the returned stream, but how can I do that?