1年くらい前にGoogle Drive関連の記事を書いてたけど、久々に触りたくなったので調査再開。
- 参考記事
メソッドはFiles: getになります。
ライブラリの書き方だとdrive.files.get()
です。
スコープ指定
スコープの指定は割と多め。
https://www.googleapis.com/auth/drive
https://www.googleapis.com/auth/drive.file
https://www.googleapis.com/auth/drive.readonly
https://www.googleapis.com/auth/drive.metadata.readonly
https://www.googleapis.com/auth/drive.appdata
https://www.googleapis.com/auth/drive.metadata
https://www.googleapis.com/auth/drive.photos.readonly
ダウンロードする
チュートリアルのfunction listFiles
の箇所を書き換えて利用してみます。
機能的には
function dlFile
とかにリネームした方が良いでしょうが一旦動かす体なのでスルー
fileId
にGoogle DriveのファイルのIDを指定しましょう。
またtest.mp4
としてますが、ファイルの種類によって拡張子は変えてください。
dj.js
asyncfunctionlistFiles(auth){constdrive=google.drive({version:'v3',auth});constfileId=`xxxxxxxxxxxx`;//GoogleDriveのファイルIDを指定constdest=fs.createWriteStream('test.mp4','utf8');try{constres=awaitdrive.files.get({fileId:fileId,alt:'media'},{responseType:'stream'});res.data.on('data',chunk=>dest.write(chunk));res.data.on('end',()=>dest.end());//保存完了}catch(err){console.log('The API returned an error: '+err);}}
けっこうシンプルに書けますね。
実行すると手元にtest.mp4
が保存されます。
おまけ: プログレス表示
公式サンプルを参考にして書くとこんな感じになります。
dl.js
//省略asyncfunctionlistFiles(auth){constdrive=google.drive({version:'v3',auth});constfileId=`xxxxxxxxxxxx`;//GoogleDriveのファイルIDを指定constdest=fs.createWriteStream('test.mp4','utf8');letprogress=0;try{constres=awaitdrive.files.get({fileId:fileId,alt:'media'},{responseType:'stream'});res.data.on('end',()=>console.log('Done downloading file.')).on('error',err=>console.error('Error downloading file.')).on('data',d=>{progress+=d.length;if(process.stdout.isTTY){process.stdout.clearLine();process.stdout.cursorTo(0);process.stdout.write(`Downloaded ${progress} bytes`);}}).pipe(dest);}catch(err){console.log('The API returned an error: '+err);}}
- 実行
こんな感じでプログレス表示があって良いですね。
$ node dj.js
Downloaded 79767428 bytesDone downloading file.
所感
実際に使うときには、
- 1.
drive.files.list()
でフォルダ内のファイル一覧及びIDなど取得 - 2.
drive.files.get()
でダウンロード
みたいな流れが多いかなぁと思います。
ファイル保存でStreamを使うあたりがNode.jsっぽさを感じますね。