在我的Meteor服务器应用中,我正在使用此代码从Google云端硬盘下载文件
var dest = fs.createWriteStream('/data/'+data.name);
drive.files.get({
fileId: data.id,
alt: 'media',
auth: jwtClient
})
.on('end', Meteor.bindEnvironment(function() {
}))
.on('error', function(err) {
console.log('Error during download', err);
})
.pipe(dest);
如何获取下载进度?例如,我希望每30秒使用console.log()
显示下载进度我可以使用.on('数据')吗?我正在使用谷歌提供的谷歌驱动器nodejs v3。
答案 0 :(得分:0)
您可以使用文件名从drive.files.list获取文件元(id,名称,大小),然后您可以下载该文件。
使用 Node.js Quickstart for google drive进行身份验证。
我正在使用progress-stream来衡量收到的%数据。
var callAfterDownload = function (fileName, callback) {
drive.files.list({
auth: oauth2Client,
pageSize: 1,
q: 'name=\'' + fileName + '\'',
fields: 'nextPageToken, files(id, name, size)'
}, function (err, response) {
if (err) {
console.log('The API returned an error: ' + err)
callback(['Error while download'])
} else {
var files = response.files
//when only one file is matched we will download
if (files.length === 1) {
var file = files.pop()
console.log('%s (%s)', file.name, file.id)
var dest = fs.createWriteStream(file.name)
var progress = Progress({time:100, length: file.size})
//downloading matched file from drive
drive.files.get({
auth: oauth2Client,
fileId: file.id,
alt: 'media'
}).on('error', function (err) {
console.log('Error during download', err)
callback(['Error while download'])
}).pipe(progress).pipe(dest)
//checking progress of file
progress.on('progress', function(progress) {
console.log('download completed ' +progress.percentage.toFixed(2) + '%')
});
//when write stream has finally written to file
dest.on('finish', callback)
} else {
console.log('EXITING......More than one/no file exist with same name, make sure you have unique file name.')
callback()
}
}
})
}
function downloadDriveFile () {
var fileName = 'testfile.doc'
callAfterDownload(fileName, function (err) {
if(err) throw err
//your logic to do anything with the file
})
}
downloadDriveFile();