Quantcast
Viewing all articles
Browse latest Browse all 9003

Google DriveのAPIをNode.jsから触るメモ

Google Drive API v3を触ります。
google-auth-token-generatorを使ってtoken.jsonの作成をしてみる版です。

以前書いた記事も参考に: https://qiita.com/n0bisuke/items/ff1479cd14e7a0c0be0c

環境

  • Node.js v15.9.0

credentials.jsonを取得

チュートリアルを参考にAPIを有効にし、credentials.jsonを手元に保存しましょう。

https://developers.google.com/drive/api/v3/quickstart/nodejs

google-auth-token-generatorでtoken.jsonを作成

google-auth-token-generatorを使うとパーミッションをつけたtoken.jsonを作成しやすいです。

利用イメージ
Image may be NSFW.
Clik here to view.

credentials.jsonのあるディレクトリで、以下を実行します。

$ npx google-auth-token-generator

GoogleDriveを選択し、パーミッションを選択して進めましょう。

ファイルの一覧取得のパーミッションはdrive.metadata.readonlyになります。

https://www.googleapis.com/auth/drive.metadata.readonly

token.jsonが保存されます。

app.jsを作成

credentials.jsontoken.jsonと同じディレクトリにapp.jsを作成する想定です。

app.js
'use strict';constfs=require('fs');const{google}=require('googleapis');constgoogleAuth=()=>{constCREDENTIALS_PATH='credentials.json';constTOKEN_PATH='token.json';constcredentials=JSON.parse(fs.readFileSync(CREDENTIALS_PATH,'utf8'));consttoken=JSON.parse(fs.readFileSync(TOKEN_PATH,'utf8'));const{client_secret,client_id,redirect_uris}=credentials.installed;constoAuth2Client=newgoogle.auth.OAuth2(client_id,client_secret,redirect_uris[0]);oAuth2Client.setCredentials(token);returnoAuth2Client;};(async()=>{constauth=googleAuth();constdrive=google.drive({version:'v3',auth});try{constres=awaitdrive.files.list({pageSize:10,fields:'nextPageToken, files(id, name)',});constfiles=res.data.files;if(files.length){console.log('Files:');files.map((file)=>console.log(`${file.name} (${file.id})`));}else{console.log('No files found.');}}catch(error){console.log('The API returned an error: '+error);}})();
$ node app.js

参考記事


Viewing all articles
Browse latest Browse all 9003

Trending Articles