node.jsrackspace-cloudfilespkgcloud

Get buffer from Rackspace download using pkgcloud


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?


Solution

  • .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);
    });