Quantcast
Channel: Node.jsタグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 8691

Node.jsでGoogle Drive上のファイルをダウンロードする (Google Drive API v3)

$
0
0

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っぽさを感じますね。

参考: Node.js Stream を使いこなす


Viewing all articles
Browse latest Browse all 8691

Trending Articles