1

This may not be possible but I am trying to return a buffer object of an image on Rackspace using the pkgcloud module without having to write to the filesystem. I've seen this done before however both examples show piping the download to the File System.

    function get() {
        return new Promise(function (resolve, reject) {
            _this._RackClient.download(options, function(err, results) {
                if (err !== null) {
                    return reject(err);
                    console.log("Errow Downloading:", err);
                }
                resolve(buffer);
            });
        });
    }
    return get();

This is ideally how I would like it to work but there currently is not a body present in the request. Can I use a stream.passThrough() and return that similar to uploading a buffer?

mcclaskiem
  • 394
  • 1
  • 15

1 Answers1

1

.download() returns a Readable stream, so it should just be a matter of buffering that output. For example:

var stream = _this._RackClient.download(options);
var buf = [];
var nb = 0;
var hadErr = false;
stream.on('data', function(chunk) {
  buf.push(chunk);
  nb += chunk.length;
}).on('end', function() {
  if (hadErr)
    return;
  switch (buf.length) {
    case 0:
      return resolve(new Buffer(0));
    case 1:
      return resolve(buf[0]);
    default:
      return resolve(Buffer.concat(buf, nb));
  }
}).on('error', function(err) {
  hadErr = true;
  reject(err);
});
mscdex
  • 104,356
  • 15
  • 192
  • 153
  • this worked in getting data correctly but im curious what the switch statement is handling since it doesn't seem to be the correct buffer. @mscdex – mcclaskiem Apr 06 '16 at 17:30
  • What do you mean by "the correct buffer?" `buf` just stores the chunks as they come in and the `switch` is just a bit of an optimization to avoid calling `Buffer.concat()` unless necessary. – mscdex Apr 06 '16 at 18:06
  • Ya that makes sense I found out that the rackclient was getting wrong arguments from Parse-Server – mcclaskiem Apr 06 '16 at 18:12
  • Hi, when I do this, I create an video without length – oihi08 Feb 12 '18 at 13:57