diff --git a/README.md b/README.md index 0b3d421..e6b2034 100644 --- a/README.md +++ b/README.md @@ -71,8 +71,9 @@ async.series([ }); }, - function(cb){ + function (cb){ // and now we're going to download that file we just uploaded + // method 1 : use Buffer to concatenate each chunks kloudless.files.contents({ "account_id": accountId, "file_id": fileId @@ -82,17 +83,34 @@ async.series([ } var filecontents = ''; console.log("got the filestream:"); - filestream.on('data', function(chunk) { + filestream.on('data', function (chunk) { console.log("reading in data chunk..."); console.log(chunk); - filecontents += chunk; + filecontents = Buffer.concat([filecontents, chunk]); }); - filestream.on('end',function() { + filestream.on('end', function () { console.log("finished reading file!"); - console.log(filecontents); + fs.writeFile("download.jpg", filecontents, function (err) { + console.log('write file error:' + err); + }); cb(); }); }); + }, + function (cb) { + // and now we're going to download that file we just uploaded + // method 2 : pipe the filestream directly + kloudless.files.contents({ + "account_id": accountId, + "file_id": fileId + }, function (err, filestream) { + if (err) { + return console.log("Files contents: " + err); + } + console.log("got the filestream:"); + filestream.pipe(fs.createWriteStream('download_2.jpg')); + cb(); + }); } ]); ``` diff --git a/lib/resources.js b/lib/resources.js index 8a1c2dd..9206647 100644 --- a/lib/resources.js +++ b/lib/resources.js @@ -41,7 +41,6 @@ BaseResource.prototype = { charEncoding = charEncoding || 'utf-8'; if (!parse && statusCodeType == '2') { - res.setEncoding('binary'); return callback(null, res, res); } else { res.setEncoding(charEncoding); diff --git a/test/index.js b/test/index.js index 886f02e..3543fd4 100644 --- a/test/index.js +++ b/test/index.js @@ -3,7 +3,8 @@ var kloudless = require('../lib/kloudless')(process.env.API_KEY || 'your-api-key-here') , async = require('async') , fs = require('fs') - , path = require('path'); + , path = require('path') + , assert = require('assert'); if (process.env.API_HOST) kloudless.setHost(process.env.API_HOST, process.env.API_PORT || 443); @@ -154,22 +155,13 @@ async.waterfall([ if (err) { return cb('Files contents: ' + err); } - var filecontents = ''; + console.log('got the filestream:'); - filestream.on('data', function(chunk){ - console.log('reading in data chunk...'); - console.log(chunk); - filecontents += chunk; - }); - filestream.on('end',function(){ - console.log('finished reading file!'); - if (filecontents === fileBuffer.toString()) { - console.log('files contents test pass'); - return cb(null); - } - else { - return cb("File contents fail test: " + filecontents) - } + filestream.on('readable', function () { + var buffer = filestream.read(); + assert.deepStrictEqual(buffer, fileBuffer); + console.log('files contents test pass'); + return cb(null); }); }); },