NodeJS - 从Google云端硬盘下载

时间:2016-03-29 15:14:26

标签: javascript node.js google-drive-api fs

我有这段代码是为了从Google Drive下载文件:

function downloadDrive(fileId, callback) {
  var fileExt = fileId.split(".");
  var file = Date.now() + "." + fileExt[fileExt.length - 1];
  var dest = fs.createWriteStream("./files/"+file);
  service.files.get({
    auth: oauth2Client,
    fileId: fileExt[0],
    alt: "media"
  })
  .on("finish", function() {
    callback(file);
  })
  .on("error", function(err) {
    console.log("Error during download", err);
  })
  .pipe(dest);
}

它适用于小文件~500Mb。但是,当试图下载一个相当大的gzip文件~3Gb时,它会引发以下错误。

buffer.js:23
  const ui8 = new Uint8Array(size);
              ^

RangeError: Invalid typed array length
    at new Uint8Array (native)
    at createBuffer (buffer.js:23:15)
    at allocate (buffer.js:98:12)
    at new Buffer (buffer.js:53:12)
    at Function.Buffer.concat (buffer.js:225:16)
    at BufferList.copy (/Synology/server_Metagenomics/server/node_modules/googleapis/node_modules/google-auth-library/node_modules/request/node_modules/bl/bl.js:124:21)
    at BufferList.slice (/Synology/server_Metagenomics/server/node_modules/googleapis/node_modules/google-auth-library/node_modules/request/node_modules/bl/bl.js:99:15)
    at BufferList.toString (/Synology/server_Metagenomics/server/node_modules/googleapis/node_modules/google-auth-library/node_modules/request/node_modules/bl/bl.js:166:15)
    at Request.<anonymous> (/Synology/server_Metagenomics/server/node_modules/googleapis/node_modules/google-auth-library/node_modules/request/request.js:1035:36)
    at emitOne (events.js:82:20)
    at Request.emit (events.js:169:7)

我没有找到很多有关它的信息。发生了什么事?

1 个答案:

答案 0 :(得分:1)

您可以尝试以下下载文件。该错误似乎是因为您正在下载大文件。

var filename = 'zzz.txt';
var proxyUrl = "http://" + user + ":" + password + "@" + host + ":" + port;
var token = 'YOUR_TOKEN';

var req = request.get('https://www.googleapis.com/drive/v3/files/YOUR_FILE_ID?alt=media', {
    'auth': {
        'bearer': token
    },
    'proxy': proxyUrl
}).on('response', function(res) {

// create file write stream
var fws = fs.createWriteStream(filename);

// setup piping
res.pipe(fws);

res.on('err', function() {
    console.log("error occured.....");
});

res.on('end', function() {
    console.log('Done');
    // go on with processing
});
});